diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..26e4e78f59305d4894f7058c0be00f8438108a9d
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,63 @@
+Current authors:
+
+Emmanuel Milou <emmanuel dot milou at savoirfairelinux dot com>
+	- ALSA implementation ( replaces portaudio )
+	- Dynamic loading of audio codecs ( shared libraries )
+	- Debian packages
+	- GTK client error handling
+	- Plus many portions of code in sflphoned and sflphone-gtk 
+	- Test and debugging
+
+Alexandre Bourget <alexandre dot bourget at savoirfairelinux dot com>
+	- IAX implementation
+
+Guillaume Carmel-Archambault <guillaume.carmel-archambault at savoirfairelinux dot com>
+	- Presence 
+	- Contacts
+Yun Liu <yun.liu at savoirfairelinux dot com>
+	- Change sip library to pjsip
+        - Support multiple accounts registration
+        - Add chinese translation
+        - Many portions of test and debugging
+ 
+Polytechnic School of Montreal:
+  - Jean-Francois Blanchard-Dionne <jean-francois.blanchard-dionne at polymtl dot ca>
+  - Ala Eddine Limame <ala-eddine.limame at polymtl dot ca>
+  - Alexis S. Bourrelle <bourrelle at polymtl dot ca>
+  - Marilyne Mercier <marilyne.mercier at polymtl dot ca>
+  - Jean Tessier <jean.tessier at polymtl dot ca>
+	- Video layer implementation
+	- Video conference
+
+Pierre-Luc Beaudoin <pierre-luc.beaudoin at savoirfairelinux dot com>
+  - Many portions of code
+  - GTK client implementation
+
+Former authors:
+
+Yan Morin <yan dot morin at savoirfairelinux dot com>
+	- zeroconf integration
+	- sflphoned deamon
+	- add and improve sip core feature
+	- tests and debugging
+
+Jerome Oufella <jerome dot oufella at savoirfairelinux dot com>
+	- Many portions of code and bug fixes
+
+Julien Plissonneau Duquene <... at savoirfairelinux dot com>
+	- autotools cleanups
+
+Jean-Philippe Barrette-LaPierre 
+	- Autotools support and portions of code
+
+Laurielle Lea
+	- Implementation of SFLphone
+
+Sherry Yang <syangs04 at yahoo dot com>
+
+Imran Akbar <imr at stanford dot edu>
+	- Working on Win32 port
+
+Contributors:
+
+Mikael Magnusson
diff --git a/sflphone-client-gnome/sflphone.desktop.in b/sflphone-client-gnome/sflphone.desktop.in
index 2fde3130f21d8ac551f24c7e3f4ab1598fe6bb1c..f621e8a166a35065184b98aa2088285c9afa6205 100644
--- a/sflphone-client-gnome/sflphone.desktop.in
+++ b/sflphone-client-gnome/sflphone.desktop.in
@@ -1,5 +1,4 @@
 [Desktop Entry]
-Encoding=UTF-8
 Name=SFLphone GNOME VoIP client
 GenericName=Telephone
 Comment=Call and receive calls with SIP or IAX protocols
diff --git a/sflphone-client-gnome/src/Makefile.am b/sflphone-client-gnome/src/Makefile.am
index fede093cac4ce350c9cc7a4abdb0a4c2ea45f1aa..a483cc3fc1effe5f3a465b60973f26c2cd0a26b9 100644
--- a/sflphone-client-gnome/src/Makefile.am
+++ b/sflphone-client-gnome/src/Makefile.am
@@ -37,7 +37,7 @@ sflphone_client_gnome_LDADD = $(DEPS_LIBS) $(NOTIFY_LIBS) $(SFLPHONEGTK_LIBS) $(
 # add symbolic link	     
 install-exec-local:
 	echo $(prefix); echo $(bindir); echo $(datadir); echo $(libdir)
-	cd $(bindir); ln -sf sflphone-client-gnome sflphone 
+	cd $(DESTDIR)$(bindir); ln -sf sflphone-client-gnome sflphone 
 
 uninstall-local:
-	-test -h $(bindir)/sflphone && rm $(bindir)/sflphone
+	-test -h $(DESTDIR)$(bindir)/sflphone && rm $(DESTDIR)$(bindir)/sflphone
diff --git a/sflphone-client-gnome/src/dbus/dbus.c b/sflphone-client-gnome/src/dbus/dbus.c
index 4caf79f99b23774a2be56cc7602b3757b3f378e4..4a827626394e972a86a24b156ea5d37bec1c6858 100644
--- a/sflphone-client-gnome/src/dbus/dbus.c
+++ b/sflphone-client-gnome/src/dbus/dbus.c
@@ -182,6 +182,10 @@ accounts_changed_cb (DBusGProxy *proxy UNUSED,
   DEBUG ("Accounts changed");
   sflphone_fill_account_list(TRUE);
   config_window_fill_account_list();
+
+  // Update the status bar in case something happened
+  // Should fix ticket #1215
+  status_bar_display_account();
 }
 
 static void
diff --git a/sflphone-client-kde/Account.h b/sflphone-client-kde/Account.h
deleted file mode 100644
index 3b8ebbcde243eaae23738eaee20efcd0255be784..0000000000000000000000000000000000000000
--- a/sflphone-client-kde/Account.h
+++ /dev/null
@@ -1,60 +0,0 @@
-#ifndef ACCOUNT_H
-#define ACCOUNT_H
-
-#include <QtCore/QString>
-#include <QtGui/QListWidgetItem>
-#include <QtGui/QColor>
-
-#include "metatypes.h"
-#include "AccountItemWidget.h"
-
-const QString account_state_name(QString & s);
-
-class Account{
-	
-private:
-
-	QString * accountId;
-	MapStringString * accountDetails;
-	QListWidgetItem * item;
-	AccountItemWidget * itemWidget;
-
-	Account();
-
-public:
-	
-	//Constructors
-	static Account * buildExistingAccountFromId(QString _accountId);
-	static Account * buildNewAccountFromAlias(QString alias);
-	
-	~Account();
-	
-	//Getters
-	bool isNew() const;
-	bool isChecked() const;
-	QString & getAccountId();
-	MapStringString & getAccountDetails() const;
-	QListWidgetItem * getItem();
-	QListWidgetItem * renewItem();
-	AccountItemWidget * getItemWidget();
-	QString getStateName(QString & state);
-	QColor getStateColor();
-	QString getStateColorName();
-	QString getAccountDetail(QString param) const;
-	QString getAlias();
-	
-	//Setters
-	void initAccountItem();
-	void setAccountId(QString id);
-	void setAccountDetails(MapStringString m);
-	void setAccountDetail(QString param, QString val);
-	
-	//Operators
-	bool operator==(const Account&)const;
-	
-	
-};
-
-
-
-#endif
\ No newline at end of file
diff --git a/sflphone-client-kde/AccountList.h b/sflphone-client-kde/AccountList.h
deleted file mode 100644
index 846ce3be6928e206bf78adb99f05bf9381f13388..0000000000000000000000000000000000000000
--- a/sflphone-client-kde/AccountList.h
+++ /dev/null
@@ -1,47 +0,0 @@
-#ifndef ACCOUNT_LIST_H
-#define ACCOUNT_LIST_H
-
-
-#include <QtCore/QVector>
-
-#include "Account.h"
-
-class AccountList{
-	
-private:
-
-	QVector<Account *> * accounts;
-	static QString firstAccount;
-
-public:
-
-	//Constructors
-	AccountList(QStringList & _accountIds);
-	AccountList();
-	~AccountList();
-	
-	//Getters
-	QVector<Account *> & getAccounts();
-	Account * getAccountById(const QString & id) const;
-	QVector<Account *>  getAccountByState(QString & state);
-	Account * getAccountByItem(QListWidgetItem * item);
-	int size();
-	Account * firstRegisteredAccount() const;
-	
-	//Setters
-	Account * addAccount(QString & alias);
-	void removeAccount(Account * account);
-	void removeAccount(QListWidgetItem * item);
-	void setAccountFirst(Account * account);
-
-	//Operators
-	Account & operator[] (int i);
-	const Account & operator[] (int i) const;
-	QVector<Account *> registeredAccounts() const;
-	void update();
-};
-
-
-
-
-#endif
\ No newline at end of file
diff --git a/sflphone-client-kde/CMakeLists.txt b/sflphone-client-kde/CMakeLists.txt
index 15937ac1976fac0c2d5aad0f173bf47c9cf5ddd6..2b41f54214fc01961621d8b916ba31280ab210da 100644
--- a/sflphone-client-kde/CMakeLists.txt
+++ b/sflphone-client-kde/CMakeLists.txt
@@ -2,14 +2,14 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
 
 PROJECT(sflphone-client-kde)
 
-SET(LOCAL_CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules/")
+SET(LOCAL_CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/")
 SET(CMAKE_MODULE_PATH "${LOCAL_CMAKE_MODULE_PATH}")
 
 # --- custom targets: ---
 INCLUDE( ${LOCAL_CMAKE_MODULE_PATH}/TargetDistclean.cmake  REQUIRED)
 
 FIND_PACKAGE ( Kabc REQUIRED )
-FIND_PACKAGE ( PkgConfig REQUIRED )
+# FIND_PACKAGE ( PkgConfig REQUIRED )
 FIND_PACKAGE ( KDE4 REQUIRED )
 FIND_PACKAGE ( Qt4 REQUIRED )
 
@@ -22,173 +22,10 @@ INCLUDE_DIRECTORIES ( ${KDE4_INCLUDES} ${QT_INCLUDES} )
 INCLUDE (  ${CMAKE_ROOT}/Modules/CheckIncludeFiles.cmake  )
 INCLUDE(   ${QT_USE_FILE}   )
 
-ADD_DEFINITIONS(${KDE4_DEFINITIONS} ${QT_DEFINITIONS} -fexceptions -DDATA_INSTALL_DIR="\\\"${DATA_INSTALL_DIR}\\\"" )
-
-
-
-#pkg_check_modules(LIBSEXY libsexy>=0.1)
-#pkg_check_modules(KDEPIM kdepimlibs5-dev REQUIRED)
-
-
-
-
-SET(
-	sflphone_client_kde_SRCS
-	sflphone_kdeview.cpp
-	SFLPhone.cpp
-	ConfigDialog.cpp
-	main.cpp
-	sflphone_const.h
-	Account.cpp
-	AccountList.cpp
-	Call.cpp
-	CallList.cpp
-	configurationmanager_interface_singleton.cpp
-	callmanager_interface_singleton.cpp
-	instance_interface_singleton.cpp
-	AccountWizard.cpp
-	AccountItemWidget.cpp
-	ActionSetAccountFirst.cpp
-	Contact.cpp
-	ContactItemWidget.cpp
-)
- 
-
-# generate rules for building source files from the resources
- 
-SET(QtApp_RCCS resources.qrc)
-
-QT4_ADD_RESOURCES(QtApp_RCC_SRCS ${QtApp_RCCS})
-
-
-# kde4_automoc(${sflphone_client_kde_SRCS})
-
-KDE4_ADD_UI_FILES(sflphone_client_kde_SRCS sflphone_kdeview_base.ui ConfigDialog.ui)
-
-# Build dbus interfaces
-
-# configuration manager interface
-
-SET ( configurationmanager_xml  ${CMAKE_CURRENT_SOURCE_DIR}/../sflphone-common/src/dbus/configurationmanager-introspec.xml )
-
-SET_SOURCE_FILES_PROPERTIES(
-   ${configurationmanager_xml}
-   PROPERTIES 
-   CLASSNAME ConfigurationManagerInterface
-   INCLUDE "metatypes.h") 
-
-QT4_ADD_DBUS_INTERFACE(
-   sflphone_client_kde_SRCS 
-   ${configurationmanager_xml}
-   configurationmanager_dbus_interface)
-
-# call manager interface
-
-SET ( callmanager_xml  ${CMAKE_CURRENT_SOURCE_DIR}/../sflphone-common/src/dbus/callmanager-introspec.xml )
-
-SET_SOURCE_FILES_PROPERTIES(
-   ${callmanager_xml}
-   PROPERTIES 
-   CLASSNAME CallManagerInterface
-   INCLUDE "metatypes.h") 
-
-QT4_ADD_DBUS_INTERFACE(
-   sflphone_client_kde_SRCS 
-   ${callmanager_xml}
-   callmanager_dbus_interface)
-
-# instance interface
-
-SET ( instance_xml  ${CMAKE_CURRENT_SOURCE_DIR}/../sflphone-common/src/dbus/instance-introspec.xml )
-
-SET_SOURCE_FILES_PROPERTIES(
-   ${instance_xml}
-   PROPERTIES 
-   CLASSNAME InstanceInterface
-   INCLUDE "metatypes.h") 
-   
-QT4_ADD_DBUS_INTERFACE(
-   sflphone_client_kde_SRCS 
-   ${instance_xml}
-   instance_dbus_interface)
-
-
-# kde4_add_kcfg_files(sflphone_client_kde_SRCS settings.kcfgc )
-
-KDE4_ADD_EXECUTABLE(sflphone-client-kde ${sflphone_client_kde_SRCS} ${QtApp_RCC_SRCS})
-
-SET ( KDE4_KABC_LIBS  -lkabc )
-TARGET_LINK_LIBRARIES(sflphone-client-kde ${KDE4_KDEUI_LIBS} ${KDE4_KIO_LIBS} ${KDE4_KABC_LIBS})
-
-
-# ADD_CUSTOM_COMMAND(OUTPUT  "${CMAKE_CURRENT_BUILD_DIR}/sflphone.1"
-#                    DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod"
-#                    COMMAND /bin/pod2man
-#                    ARGS --section=1 --release=${VERSION} --center "" "${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod" > "${CMAKE_CURRENT_BUILD_DIR}/sflphone.1"
-#                    COMMENT "Compiling manpage of sflphone-client-kde with pod2man")
-
-
-
-# ADD_CUSTOM_COMMAND(OUTPUT  "sflphone-client-kde.1"
-# #                    DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod"
-#                    COMMAND /bin/pod2man
-#                    ARGS --section=1 --release=${VERSION} --center "" "${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod" > "${CMAKE_CURRENT_BUILD_DIR}/sflphone-client-kde.1"
-# #                    COMMENT "Compiling manpage of sflphone-client-kde with pod2man"
-#                    )
-
-
-# ADD_CUSTOM_COMMAND(OUTPUT  ${CMAKE_BINARY_DIR}/sflphone-client-kde.1
-# #                    DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod"
-#                    COMMAND /usr/bin/pod2man
-#                     ARGS --release=${VERSION} ${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod > ${CMAKE_BIANRY_DIR}/sflphone-client-kde.1
-#                    COMMENT "Compiling manpage of sflphone-client-kde with pod2man"
-# # 		              VERBATIM
-#                    )
-                   
-                   
-# ADD_CUSTOM_COMMAND(OUTPUT  ${CMAKE_CURRENT_BUILD_DIR}/test.txt
-# #                    DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod"
-#                    COMMAND cp 
-#                     ARGS ${CMAKE_CURRENT_BUILD_DIR}/test2.txt ${CMAKE_CURRENT_BUILD_DIR}/test.txt
-#                    COMMENT "Yeaaaaaaaaaaaaaahhhhhhh"
-# # 		              VERBATIM
-#                    )
-                   
-#                    ADD_CUSTOM_COMMAND(
-#     OUTPUT ${CMAKE_BINARY_DIR}/test.txt
-#     COMMAND cp ${CMAKE_BINARY_DIR}/test2.txt ${CMAKE_BINARY_DIR}/test.txt
-#     COMMENT "Yeaaaaaaaaaaaaaahhhhhhh"
-#     )
-
-# FILE(WRITE "${CMAKE_BINARY_DIR}/sflphone-client-kde.1")
-                   
-# execute_process(COMMAND pod2man --release=${VERSION} ${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.pod
-#                 OUTPUT_FILE sflphone-client-kde.1)
-
-# execute_process(COMMAND "cp ${CMAKE_CURRENT_BUILD_DIR}/test2.txt ${CMAKE_CURRENT_BUILD_DIR}/test.txt")
-
 
+add_subdirectory(src)
 add_subdirectory(doc)
 add_subdirectory(man)
-
-########### install files ###############
-
-# SET ( HTML_INSTALL_DIR  ${CMAKE_INSTALL_PREFIX}/share/doc/kde/HTML )
-#SET ( MANPAGES_INSTALL_DIR  /usr/share/man )
-
-INSTALL(TARGETS sflphone-client-kde DESTINATION ${BIN_INSTALL_DIR})
-
-INSTALL( FILES sflphone-client-kde.desktop  DESTINATION  ${XDG_APPS_INSTALL_DIR} )
-# INSTALL( FILES sflphone_kde.kcfg  DESTINATION  ${KCFG_INSTALL_DIR} )
-INSTALL( FILES sflphone-client-kdeui.rc  DESTINATION  ${DATA_INSTALL_DIR}/sflphone-client-kde )
-#INSTALL ( CODE "FILE(MAKE_DIRECTORY ${HTML_INSTALL_DIR}/en/sflphone-client-kde)"  )
-#INSTALL( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc/ DESTINATION ${HTML_INSTALL_DIR} )
-# INSTALL( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc/ DESTINATION ${HTML_INSTALL_DIR} )
-#KDE4_CREATE_MANPAGE( ${CMAKE_CURRENT_SOURCE_DIR}/doc/en/sflphone-client-kde/index.docbook INSTALL_DESTINATION ${MAN_INSTALL_DIR} SUBDIR  )
-#INSTALL ( CODE "FILE(MAKE_DIRECTORY ${HTML_INSTALL_DIR}/en/sflphone-client-kde)"  )
-#INSTALL( FILES ${CMAKE_CURRENT_BUILD_DIR}/sflphone.1 ${CMAKE_CURRENT_SOURCE_DIR}/man/sflphone-client-kde.1   DESTINATION  ${MANPAGES_INSTALL_DIR}/man1 )
-# INSTALL( FILES ${CMAKE_BINARY_DIR}/sflphone-client-kde.1  DESTINATION  ${MAN_INSTALL_DIR}/man1 )
-# kde4_create_handbook(${CMAKE_CURRENT_SOURCE_DIR}/doc/en/sflphone-client-kde/index.docbook INSTALL_DESTINATION ${HTML_INSTALL_DIR}/en)
+add_subdirectory(data)
 
 
-#INSTALL ( CODE "MESSAGE (\"ton pere\")" )
\ No newline at end of file
diff --git a/sflphone-client-kde/CallList.h b/sflphone-client-kde/CallList.h
deleted file mode 100644
index 8b01961f0f984c75c84fa72b23fbb82be08696d7..0000000000000000000000000000000000000000
--- a/sflphone-client-kde/CallList.h
+++ /dev/null
@@ -1,39 +0,0 @@
-#ifndef CALL_LIST_H
-#define CALL_LIST_H
-
-#include <QtCore/QVector>
-#include <QtCore/QString>
-#include <QtGui/QListWidgetItem>
-
-#include "Call.h"
-
-class CallList
-{
-private:
-	QVector<Call *> * calls;
-	int callIdCpt;
-
-public:
-
-	CallList();
-	~CallList();
-
-	Call * findCallByItem(const QListWidgetItem * item);
-	Call * findCallByHistoryItem(const QListWidgetItem * item);
-	Call * findCallByCallId(const QString & callId);
-	Call * operator[](const QListWidgetItem * item);
-	Call * operator[](const QString & callId);
-	Call * operator[](int ind);
-
-	Call * addDialingCall(const QString & peerName = "");
-	Call * addIncomingCall(const QString & callId/*, const QString & from, const QString & account*/);
-	Call * addRingingCall(const QString & callId);
-
-	QString getAndIncCallId();
-	int size();
-
-
-};
-
-
-#endif
\ No newline at end of file
diff --git a/sflphone-client-kde/INSTALL b/sflphone-client-kde/INSTALL
new file mode 100644
index 0000000000000000000000000000000000000000..c3ff7117560cc3dfc0ebfcac9372724969446242
--- /dev/null
+++ b/sflphone-client-kde/INSTALL
@@ -0,0 +1,55 @@
+Installation Instructions
+*************************
+
+Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005 Free
+Software Foundation, Inc.
+
+This file is free documentation; the Free Software Foundation gives
+unlimited permission to copy, distribute and modify it.
+
+Basic Installation
+==================
+
+These are generic installation instructions.
+
+
+To install the appplication, type the following commands in a console, while in the root directory of this application:
+
+	.config.sh
+	cd build
+	make
+	sudo make install
+
+Explaination
+==================
+
+	.config.sh
+
+This script will configure and prepare the compilation and installation of the program.
+
+All needed files will be built in "build" directory.
+So you have to go to this directory:
+
+	cd build
+
+Then execute the Makefile, to compile the application (src, doc...)
+
+	make
+
+Then install it all using:
+
+	sudo make install
+	
+You have to use "sudo" to be able to install the program in a protected directory (which is the case by default and most of the time).
+Therefore it will ask for your system password.
+If you don't have this password or for any reason you want to install the program in a non-protected directory, refer to the Options below.
+
+
+Options
+==================
+
+You can change the prefix of the installation using:
+
+	.config.sh -DCMAKE_INSTALL_PREFIX="expected_prefix_directory"
+
+By default, it is set to /usr.
\ No newline at end of file
diff --git a/sflphone-client-kde/README b/sflphone-client-kde/README
index a5f3a30788f36e571a14ffba50c84111984cb6e0..3db5b30eedc0bcf455d2c3d2a050d077ae5f6c34 100644
--- a/sflphone-client-kde/README
+++ b/sflphone-client-kde/README
@@ -1,15 +1,27 @@
-!!!!!ATTENTION!!!!!
+Welcome to SFLphone KDE Client!
 
-Before starting the build you may need to setup the KDE4 environment variables.
-To do this open Project->Project Options and then look at the "Run" and the "Make" 
-pages. Each of these two has an environment variables widget in which you have
-to fill in the right values for the variables already listed.
+For install instructions, read the INSTALL file, in this directory.
 
-After setting up the variables you'll also need to run cmake inside the build
-directory. This can not be done by kdevelop as a KDE4 environment is needed
-when running cmake to find KDE4. Open the integrated konsole and change to the build
-subdirectory. Then setup a KDE4 environment and run "cmake ../".
 
-More information how to setup a KDE4 development environment can be found on
-http://techbase.kde.org/Getting_Started/Increased_Productivity_in_KDE4_with_Scripts
+Copyright (c) Savoir-faire Linux, Inc 2004-2009
+  <sflphoneteam@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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+Refer to the development site for further information: http://dev.savoirfairelinux.net/sflphone
+
+
+Thank you
diff --git a/sflphone-client-kde/SFLPhone.h b/sflphone-client-kde/SFLPhone.h
deleted file mode 100644
index ccf9e46da73ad8bce8e5ac27cd589e1b136d438e..0000000000000000000000000000000000000000
--- a/sflphone-client-kde/SFLPhone.h
+++ /dev/null
@@ -1,56 +0,0 @@
-#ifndef SFLPHONE_H
-#define SFLPHONE_H
-
-#include <QtCore/QString>
-#include <QtCore/QVector>
-#include <QtGui/QListWidgetItem>
-#include <QtGui/QKeyEvent>
-#include <QErrorMessage>
-#include <QSystemTrayIcon>
-
-#include <KXmlGuiWindow>
-
-#include "ui_sflphone_kdeview_base.h"
-#include "ConfigDialog.h"
-#include "CallList.h"
-#include "AccountWizard.h"
-#include "Contact.h"
-#include "sflphone_kdeview.h"
-
-
-class ConfigurationDialog;
-class sflphone_kdeView;
-
-class SFLPhone : public KXmlGuiWindow
-{
-
-Q_OBJECT
-
-private:
-	sflphone_kdeView * view;
-	QMenu *trayIconMenu;
-	bool iconChanged;
-	QSystemTrayIcon *trayIcon;
-
-protected:
-	virtual bool queryClose();
-	virtual void changeEvent(QEvent * event);
-
-public:
-	SFLPhone(QWidget *parent = 0);
-	~SFLPhone();
-	void setupActions();
-	void sendNotif(QString caller);
-	void putForeground();
-	void trayIconSignal();
-	
-	
-private slots:
-	void on_trayIcon_activated(QSystemTrayIcon::ActivationReason reason);
-	void on_trayIcon_messageClicked();
-
-
-};
-
-#endif
- 
diff --git a/sflphone-client-kde/cmake_modules/FindKabc.cmake b/sflphone-client-kde/cmake/FindKabc.cmake
similarity index 100%
rename from sflphone-client-kde/cmake_modules/FindKabc.cmake
rename to sflphone-client-kde/cmake/FindKabc.cmake
diff --git a/sflphone-client-kde/cmake_modules/FindQt4.cmake b/sflphone-client-kde/cmake/FindQt4.cmake
similarity index 100%
rename from sflphone-client-kde/cmake_modules/FindQt4.cmake
rename to sflphone-client-kde/cmake/FindQt4.cmake
diff --git a/sflphone-client-kde/cmake/TargetDistclean.cmake b/sflphone-client-kde/cmake/TargetDistclean.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..8fdf46feeeec3fdd99189acb1086128a6afe28c2
--- /dev/null
+++ b/sflphone-client-kde/cmake/TargetDistclean.cmake
@@ -0,0 +1,81 @@
+ 
+# add custom target distclean
+# cleans and removes cmake generated files etc.
+# Jan Woetzel 04/2003
+#
+
+IF (UNIX)
+  ADD_CUSTOM_TARGET (distclean @echo cleaning for source distribution)
+  SET(DISTCLEANED
+#    cmake.depends
+#    cmake.check_depends
+#    CMakeCache.txt
+#    cmake.check_cache
+#    *.cmake
+#    Makefile
+#    core core.*
+#    gmon.out
+#    *~
+#    *_automoc.cpp.files
+#    *_automoc.cpp
+#    moc_*.cpp
+#    ui_*.h
+#    *.moc
+#    qrc_resources.cxx
+#    *_dbus_interface.cpp
+#    *_dbus_interface.h
+#    sflphone-client-kde
+#    sflphone-client-kde.shell
+#    install_manifest.txt
+#    *.1
+   CMakeCache.txt
+   *.cmake
+   Makefile
+   CMakeFiles
+   CMakeTmp
+   install_manifest.txt
+   man/*.cmake
+   man/Makefile
+   man/CMakeFiles
+   man/*.html
+   man/*.1
+   doc/*.cmake
+   doc/Makefile
+   doc/CMakeFiles
+   doc/*.bz2
+   data/*.cmake
+   data/Makefile
+   data/CMakeFiles
+   src/*.cmake
+   src/Makefile
+   src/CMakeFiles
+   src/*.o
+   src/moc_*.cpp
+   src/ui_*.h
+   src/qrc_*.cxx
+   src/*_dbus_interface.cpp
+   src/*_dbus_interface.h
+   src/*_automoc.cpp.files
+   src/*_automoc.cpp
+   src/sflphone-client-kde
+   src/sflphone-client-kde.shell
+  )
+  
+  SET(DISTCLEANED_REC
+   *.cmake 
+   Makefile
+   CMakeFiles
+  )
+  
+  ADD_CUSTOM_COMMAND(
+    DEPENDS clean
+    COMMENT "distribution clean"
+    COMMAND rm
+    ARGS    -Rf CMakeTmp CMakeFiles ${DISTCLEANED}
+#     COMMAND find
+#     ARGS ". \( -name 'Makefile' -o -name 'CMakeFiles' \) -exec rm -rf {} \;"
+    TARGET  distclean
+  )
+ENDIF(UNIX)
+
+
diff --git a/sflphone-client-kde/cmake_modules/TargetDistclean.cmake b/sflphone-client-kde/cmake_modules/TargetDistclean.cmake
deleted file mode 100644
index ace5efc5dcdea0f0e30e8c38e11e4c15f1e4523e..0000000000000000000000000000000000000000
--- a/sflphone-client-kde/cmake_modules/TargetDistclean.cmake
+++ /dev/null
@@ -1,51 +0,0 @@
- 
-# add custom target distclean
-# cleans and removes cmake generated files etc.
-# Jan Woetzel 04/2003
-#
-
-IF (UNIX)
-  ADD_CUSTOM_TARGET (distclean @echo cleaning for source distribution)
-  SET(DISTCLEANED
-   cmake.depends
-   cmake.check_depends
-   CMakeCache.txt
-   cmake.check_cache
-   *.cmake
-   Makefile
-   core core.*
-   gmon.out
-   *~
-   *_automoc.cpp.files
-   *_automoc.cpp
-   moc_*.cpp
-   ui_*.h
-   *.moc
-   qrc_resources.cxx
-   *_dbus_interface.cpp
-   *_dbus_interface.h
-   sflphone-client-kde
-   sflphone-client-kde.shell
-   install_manifest.txt
-   *.1
-   man/*.cmake
-   man/Makefile
-   man/CMakeFiles
-   man/*.html
-   man/*.1
-   doc/*.cmake
-   doc/Makefile
-   doc/CMakeFiles
-   doc/*.bz2
-  )
-  
-  ADD_CUSTOM_COMMAND(
-    DEPENDS clean
-    COMMENT "distribution clean"
-    COMMAND rm
-    ARGS    -Rf CMakeTmp CMakeFiles ${DISTCLEANED}
-    TARGET  distclean
-  )
-ENDIF(UNIX)
-
-
diff --git a/sflphone-client-kde/config.sh b/sflphone-client-kde/config.sh
new file mode 100755
index 0000000000000000000000000000000000000000..931c28bc5e15f6222cbceb638bcdbc6357ca29ac
--- /dev/null
+++ b/sflphone-client-kde/config.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+function autocmd()
+{
+    echo "Running ${1}..."
+        $* || {
+            echo "Error running ${1}"
+                exit 1
+        }
+}
+
+if [ ! -d "build" ]; then
+	mkdir build
+fi
+
+cd build
+
+autocmd cmake $@ ..
+
+echo $@
+
+echo "**********************************************"
+echo "Configuration done!" 
+echo "Run \`cd build\' to go to the build directory."
+echo "Then run \`make\'to build the software."
+echo "**********************************************"
diff --git a/sflphone-client-kde/data/CMakeLists.txt b/sflphone-client-kde/data/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c7fb198d7e1bface2b84ab5c33074c2bf52a3af3
--- /dev/null
+++ b/sflphone-client-kde/data/CMakeLists.txt
@@ -0,0 +1,4 @@
+
+INSTALL( FILES sflphone-client-kde.desktop  DESTINATION  ${XDG_APPS_INSTALL_DIR} )
+INSTALL( FILES sflphone-client-kdeui.rc  DESTINATION  ${DATA_INSTALL_DIR}/sflphone-client-kde )
+
diff --git a/sflphone-client-kde/sflphone-client-kde.desktop b/sflphone-client-kde/data/sflphone-client-kde.desktop
similarity index 100%
rename from sflphone-client-kde/sflphone-client-kde.desktop
rename to sflphone-client-kde/data/sflphone-client-kde.desktop
diff --git a/sflphone-client-kde/sflphone-client-kdeui.rc b/sflphone-client-kde/data/sflphone-client-kdeui.rc
similarity index 100%
rename from sflphone-client-kde/sflphone-client-kdeui.rc
rename to sflphone-client-kde/data/sflphone-client-kdeui.rc
diff --git a/sflphone-client-kde/doc/CMakeLists.txt b/sflphone-client-kde/doc/CMakeLists.txt
index 0df9c9adac43df3a227847bff1b026bfdc98b118..9c366d939ca52853864cfe0fe473c26f17383f22 100644
--- a/sflphone-client-kde/doc/CMakeLists.txt
+++ b/sflphone-client-kde/doc/CMakeLists.txt
@@ -1,4 +1,5 @@
 ########### install files ###############
 #
 #
-kde4_create_handbook(index.docbook INSTALL_DESTINATION ${HTML_INSTALL_DIR}/en)
+
+kde4_create_handbook(index.docbook INSTALL_DESTINATION ${HTML_INSTALL_DIR}/en SUBDIR sflphone-client-kde)
diff --git a/sflphone-client-kde/doc/basic-use.docbook b/sflphone-client-kde/doc/basic-use.docbook
index cb642573e73f4ed87c11c7cc0fc6e0cfdb87a391..d089a2c123ab15ec744592a021f726121b9d49c5 100644
--- a/sflphone-client-kde/doc/basic-use.docbook
+++ b/sflphone-client-kde/doc/basic-use.docbook
@@ -27,7 +27,7 @@ To switch between those windows, click on the history and address book buttons.
 
 
 <sect1 id="basic-use-call">
-<title>Calling somebody</title>
+<title>Making a call</title>
 
 <sect2 id="basic-use-call-current">
 <title>Dialing one's number</title>
@@ -103,4 +103,14 @@ To switch between those windows, click on the history and address book buttons.
 
 
 
+<sect1 id="basic-use-config">
+<title>Configuration panel</title>
+
+<para>The configuration panel is built in accordance with KDE specifications. It is divided by options type. The panel at left shows the different option pages you can reach. Click on one of them to acceed to the corresponding page. The changes you make are not applied until you click OK or Apply. Clicking Cancel will cancel and forget every change you made since the last Apply or OK command. Be careful not to forget some changes you made in some other pages if you wanted to Cancel it. </para>
+
+<para>There is also a specific Apply button just for the account list which is useful to manage these accounts and valid your changes to see if the accounts are well registered. </para>
+
+</sect1>
+
+
 </chapter>
diff --git a/sflphone-client-kde/install.sh b/sflphone-client-kde/install.sh
deleted file mode 100755
index 651e29b308a721984267bd55efa20f9ad7b63695..0000000000000000000000000000000000000000
--- a/sflphone-client-kde/install.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/bin/sh
-
-echo "Installing SflPhone-KDE"
-echo "Creating build directory"
-mkdir build
-cd build
-echo "Executing cmake command"
-cmake ../
-echo "Executing makefile"
-make
-echo "Compile done. You may now execute build/sflphone_kde ."
\ No newline at end of file
diff --git a/sflphone-client-kde/po/sflphone-client-kde.pot b/sflphone-client-kde/po/sflphone-client-kde.pot
new file mode 100644
index 0000000000000000000000000000000000000000..0af5848a3410ca3cd5fb9146321509228ba4d4c9
--- /dev/null
+++ b/sflphone-client-kde/po/sflphone-client-kde.pot
@@ -0,0 +1,225 @@
+# SOME DESCRIPTIVE TITLE.
+# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
+# This file is distributed under the same license as the PACKAGE package.
+# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: PACKAGE VERSION\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2009-05-05 12:00-0400\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <LL@li.org>\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=CHARSET\n"
+"Content-Transfer-Encoding: 8bit\n"
+
+#: AccountWizard.cpp:163
+msgid "Account Wizard"
+msgstr ""
+
+#: AccountWizard.cpp:198
+msgid "Creation of account succeed with parameters :\n"
+msgstr ""
+
+#: AccountWizard.cpp:209
+msgid "Creation of account has failed for the reason :\n"
+msgstr ""
+
+#: AccountWizard.cpp:215
+msgid "Register of account succeed with parameters :\n"
+msgstr ""
+
+#: AccountWizard.cpp:251
+msgid "Alias : "
+msgstr ""
+
+#: AccountWizard.cpp:252
+msgid "Server : "
+msgstr ""
+
+#: AccountWizard.cpp:253
+msgid "User : "
+msgstr ""
+
+#: AccountWizard.cpp:254
+msgid "Password : "
+msgstr ""
+
+#: AccountWizard.cpp:255
+msgid "Protocol : "
+msgstr ""
+
+#: AccountWizard.cpp:256
+msgid "Mailbox : "
+msgstr ""
+
+#: AccountWizard.cpp:273
+msgid "Account Creation Wizard"
+msgstr ""
+
+#: AccountWizard.cpp:274
+msgid "Welcome to the Account creation wizard of SFLPhone"
+msgstr ""
+
+#: AccountWizard.cpp:276
+msgid "This wizard will help you setting up an account."
+msgstr ""
+
+#: AccountWizard.cpp:304
+msgid "Accounts"
+msgstr ""
+
+#: AccountWizard.cpp:305
+msgid "Please choose between those options :"
+msgstr ""
+
+#: AccountWizard.cpp:307
+msgid "Create a free SIP/IAX2 account on sflphone.org"
+msgstr ""
+
+#: AccountWizard.cpp:308
+msgid "Register an existing SIP/IAX2 account"
+msgstr ""
+
+#: AccountWizard.cpp:347
+msgid "VoIP Protocols"
+msgstr ""
+
+#: AccountWizard.cpp:348
+msgid "Choose the account type :"
+msgstr ""
+
+#: AccountWizard.cpp:350
+msgid "Create a SIP (Session Initiation Protocol) account"
+msgstr ""
+
+#: AccountWizard.cpp:351
+msgid "Create a IAX2 (InterAsterisk eXchange) account"
+msgstr ""
+
+#: AccountWizard.cpp:390
+msgid "Optionnal Email Address"
+msgstr ""
+
+#: AccountWizard.cpp:391
+msgid "This email address will be used to send your voicemail messages."
+msgstr ""
+
+#: AccountWizard.cpp:393
+msgid "Email address"
+msgstr ""
+
+#: AccountWizard.cpp:427
+msgid "SIP Account Settings"
+msgstr ""
+
+#: AccountWizard.cpp:431
+msgid "IAX2 Account Settings"
+msgstr ""
+
+#: AccountWizard.cpp:433
+msgid "Please full these settings fields."
+msgstr ""
+
+#: AccountWizard.cpp:435
+msgid "Alias *"
+msgstr ""
+
+#: AccountWizard.cpp:436
+msgid "Server *"
+msgstr ""
+
+#: AccountWizard.cpp:437
+msgid "User *"
+msgstr ""
+
+#: AccountWizard.cpp:438
+msgid "Password *"
+msgstr ""
+
+#: AccountWizard.cpp:510
+msgid "Network Address Translation (NAT)"
+msgstr ""
+
+#: AccountWizard.cpp:511
+msgid ""
+"You should probably enable this option if you're placed under a firewall :"
+msgstr ""
+
+#: AccountWizard.cpp:513
+msgid "Enable STUN"
+msgstr ""
+
+#: AccountWizard.cpp:514
+msgid "Stun Server"
+msgstr ""
+
+#: AccountWizard.cpp:548
+msgid "Account Definition Finished"
+msgstr ""
+
+#: AccountWizard.cpp:549
+msgid ""
+"After checking the settings you chose, click \"Finish\" to create the "
+"account."
+msgstr ""
+
+#: Call.cpp:96
+msgid "Transfer to : "
+msgstr ""
+
+#: SFLPhone.cpp:109
+msgid "You still have some calls open. Please close all calls before quitting."
+msgstr ""
+
+#: sflphone_kdeview.cpp:984 sflphone_kdeview.cpp:1040
+msgid "Edit before call"
+msgstr ""
+
+#: sflphone_const.h:51
+msgctxt "ton pere"
+msgid "Call"
+msgstr ""
+
+#: sflphone_const.h:52
+msgid "Hang up"
+msgstr ""
+
+#: sflphone_const.h:53
+msgid "Hold"
+msgstr ""
+
+#: sflphone_const.h:54
+msgid "Transfer"
+msgstr ""
+
+#: sflphone_const.h:55
+msgid "Record"
+msgstr ""
+
+#: sflphone_const.h:56
+msgid "Accept"
+msgstr ""
+
+#: sflphone_const.h:57
+msgid "Refuse"
+msgstr ""
+
+#: sflphone_const.h:58
+msgid "Unhold"
+msgstr ""
+
+#: sflphone_const.h:59
+msgid "Give up transfer"
+msgstr ""
+
+#: sflphone_const.h:60
+msgid "Call back"
+msgstr ""
+
+#: sflphone_const.h:61
+msgid "Give up search"
+msgstr ""
diff --git a/sflphone-client-kde/po/sflphone-client-kde_fr.po b/sflphone-client-kde/po/sflphone-client-kde_fr.po
new file mode 100644
index 0000000000000000000000000000000000000000..c02b586ab118e99401b9435e5353c0a5a31fa3fc
--- /dev/null
+++ b/sflphone-client-kde/po/sflphone-client-kde_fr.po
@@ -0,0 +1,225 @@
+# SOME DESCRIPTIVE TITLE.
+# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
+# This file is distributed under the same license as the PACKAGE package.
+# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: PACKAGE VERSION\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2009-05-05 12:00-0400\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <LL@li.org>\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=CHARSET\n"
+"Content-Transfer-Encoding: 8bit\n"
+
+#: AccountWizard.cpp:163
+msgid "Account Wizard"
+msgstr "Assistant de création de compte"
+
+#: AccountWizard.cpp:198
+msgid "Creation of account succeed with parameters :\n"
+msgstr "Compte créé avec succès avec les paramètres :\n"
+
+#: AccountWizard.cpp:209
+msgid "Creation of account has failed for the reason :\n"
+msgstr "Création de compte échouée pour raison :\n"
+
+#: AccountWizard.cpp:215
+msgid "Register of account succeed with parameters :\n"
+msgstr "Compte enregistré avec succès avec les paramètres :\n"
+
+#: AccountWizard.cpp:251
+msgid "Alias : "
+msgstr "Alias : "
+
+#: AccountWizard.cpp:252
+msgid "Server : "
+msgstr "Serveur : "
+
+#: AccountWizard.cpp:253
+msgid "User : "
+msgstr "Utilisateur : "
+
+#: AccountWizard.cpp:254
+msgid "Password : "
+msgstr "Mot de passe : "
+
+#: AccountWizard.cpp:255
+msgid "Protocol : "
+msgstr "Protocole : "
+
+#: AccountWizard.cpp:256
+msgid "Mailbox : "
+msgstr "Boîte vocale : "
+
+#: AccountWizard.cpp:273
+msgid "Account Creation Wizard"
+msgstr "Assistant de création de compte"
+
+#: AccountWizard.cpp:274
+msgid "Welcome to the Account creation wizard of SFLPhone"
+msgstr "Bienvenue dans l'assistant de création de compte de SFLPhone"
+
+#: AccountWizard.cpp:276
+msgid "This wizard will help you setting up an account."
+msgstr "Cet assistant va vous aider à créer et paramètrer un compte"
+
+#: AccountWizard.cpp:304
+msgid "Accounts"
+msgstr "Comptes"
+
+#: AccountWizard.cpp:305
+msgid "Please choose between those options :"
+msgstr "Choisissez une des options :"
+
+#: AccountWizard.cpp:307
+msgid "Create a free SIP/IAX2 account on sflphone.org"
+msgstr "Créer un compte gratuit SIP/IAX2 sur sflphone.org"
+
+#: AccountWizard.cpp:308
+msgid "Register an existing SIP/IAX2 account"
+msgstr "Enregistrer un compte SIP/IAX2 existant"
+
+#: AccountWizard.cpp:347
+msgid "VoIP Protocols"
+msgstr "Protocoles VoIP"
+
+#: AccountWizard.cpp:348
+msgid "Choose the account type :"
+msgstr "Choisissez le type de compte :"
+
+#: AccountWizard.cpp:350
+msgid "Create a SIP (Session Initiation Protocol) account"
+msgstr "Créer un compte SIP (Session Initiation Protocol)"
+
+#: AccountWizard.cpp:351
+msgid "Create a IAX2 (InterAsterisk eXchange) account"
+msgstr "Créer un compte IAX2 (InterAsterisk eXchange)"
+
+#: AccountWizard.cpp:390
+msgid "Optionnal Email Address"
+msgstr "Adresse email (optionnel)"
+
+#: AccountWizard.cpp:391
+msgid "This email address will be used to send your voicemail messages."
+msgstr "Cette adresse email sera utilisée pour l'envoi des messages vocaux et textes"
+
+#: AccountWizard.cpp:393
+msgid "Email address"
+msgstr ""
+
+#: AccountWizard.cpp:427
+msgid "SIP Account Settings"
+msgstr ""
+
+#: AccountWizard.cpp:431
+msgid "IAX2 Account Settings"
+msgstr ""
+
+#: AccountWizard.cpp:433
+msgid "Please full these settings fields."
+msgstr ""
+
+#: AccountWizard.cpp:435
+msgid "Alias *"
+msgstr ""
+
+#: AccountWizard.cpp:436
+msgid "Server *"
+msgstr ""
+
+#: AccountWizard.cpp:437
+msgid "User *"
+msgstr ""
+
+#: AccountWizard.cpp:438
+msgid "Password *"
+msgstr ""
+
+#: AccountWizard.cpp:510
+msgid "Network Address Translation (NAT)"
+msgstr ""
+
+#: AccountWizard.cpp:511
+msgid ""
+"You should probably enable this option if you're placed under a firewall :"
+msgstr ""
+
+#: AccountWizard.cpp:513
+msgid "Enable STUN"
+msgstr ""
+
+#: AccountWizard.cpp:514
+msgid "Stun Server"
+msgstr ""
+
+#: AccountWizard.cpp:548
+msgid "Account Definition Finished"
+msgstr ""
+
+#: AccountWizard.cpp:549
+msgid ""
+"After checking the settings you chose, click \"Finish\" to create the "
+"account."
+msgstr ""
+
+#: Call.cpp:96
+msgid "Transfer to : "
+msgstr ""
+
+#: SFLPhone.cpp:109
+msgid "You still have some calls open. Please close all calls before quitting."
+msgstr ""
+
+#: sflphone_kdeview.cpp:984 sflphone_kdeview.cpp:1040
+msgid "Edit before call"
+msgstr ""
+
+#: sflphone_const.h:51
+msgctxt "ton pere"
+msgid "Call"
+msgstr ""
+
+#: sflphone_const.h:52
+msgid "Hang up"
+msgstr ""
+
+#: sflphone_const.h:53
+msgid "Hold"
+msgstr ""
+
+#: sflphone_const.h:54
+msgid "Transfer"
+msgstr ""
+
+#: sflphone_const.h:55
+msgid "Record"
+msgstr ""
+
+#: sflphone_const.h:56
+msgid "Accept"
+msgstr ""
+
+#: sflphone_const.h:57
+msgid "Refuse"
+msgstr ""
+
+#: sflphone_const.h:58
+msgid "Unhold"
+msgstr ""
+
+#: sflphone_const.h:59
+msgid "Give up transfer"
+msgstr ""
+
+#: sflphone_const.h:60
+msgid "Call back"
+msgstr ""
+
+#: sflphone_const.h:61
+msgid "Give up search"
+msgstr ""
diff --git a/sflphone-client-kde/resources.qrc b/sflphone-client-kde/resources.qrc
deleted file mode 100644
index b084c4d83acbb8d4dcdb848c17f471b9c441dd21..0000000000000000000000000000000000000000
--- a/sflphone-client-kde/resources.qrc
+++ /dev/null
@@ -1,92 +0,0 @@
-<RCC>
-  <qresource prefix="images" >
-    <file>icons/sflphone.svg</file>
-    <file>icons/sflphone_notif.svg</file>
-    <file>icons/application-exit.png</file>
-    <file>icons/office-address-book.png</file>
-    <file>icons/x-office-address-book.png</file>
-    <file>icons/add.png</file>
-    <file>icons/remove.png</file>
-    <file>icons/del_off.png</file>
-    <file>icons/del_on.png</file>
-    <file>icons/accept.svg</file>
-    <file>icons/busy.svg</file>
-    <file>icons/call.svg</file>
-    <file>icons/current.svg</file>
-    <file>icons/dial.svg</file>
-    <file>icons/fail.svg</file>
-    <file>icons/hang_up.svg</file>
-    <file>icons/history2.svg</file>
-    <file>icons/history.svg</file>
-    <file>icons/hold.svg</file>
-    <file>icons/application-exit.png</file>
-    <file>icons/icon_accept.svg</file>
-    <file>icons/icon_call.svg</file>
-    <file>icons/icon_dialpad_off.svg</file>
-    <file>icons/icon_dialpad.svg</file>
-    <file>icons/icon_hangup.svg</file>
-    <file>icons/icon_hold.svg</file>
-    <file>icons/icon_rec.svg</file>
-    <file>icons/icon_unhold.svg</file>
-    <file>icons/icon_volume_off.svg</file>
-    <file>icons/icon_volume.svg</file>
-    <file>icons/incoming.svg</file>
-    <file>icons/mailbox.svg</file>
-    <file>icons/mic_25.svg</file>
-    <file>icons/mic_50.svg</file>
-    <file>icons/mic_75.svg</file>
-    <file>icons/mic.svg</file>
-    <file>icons/missed.svg</file>
-    <file>icons/outgoing.svg</file>
-    <file>icons/rec_call.svg</file>
-    <file>icons/refuse.svg</file>
-    <file>icons/ring.svg</file>
-    <file>icons/sflphone.png</file>
-    <file>icons/speaker_25.svg</file>
-    <file>icons/speaker_50.svg</file>
-    <file>icons/speaker_75.svg</file>
-    <file>icons/speaker.svg</file>
-    <file>icons/stock_person.svg</file>
-    <file>icons/transfert.svg</file>
-    <file>icons/unhold.svg</file>
-    <file>icons/accept.svg</file>
-    <file>icons/busy.svg</file>
-    <file>icons/call.svg</file>
-    <file>icons/current.svg</file>
-    <file>icons/dial.svg</file>
-    <file>icons/fail.svg</file>
-    <file>icons/hang_up.svg</file>
-    <file>icons/history2.svg</file>
-    <file>icons/history.svg</file>
-    <file>icons/hold.svg</file>
-    <file>icons/icon_accept.svg</file>
-    <file>icons/icon_call.svg</file>
-    <file>icons/icon_dialpad_off.svg</file>
-    <file>icons/icon_dialpad.svg</file>
-    <file>icons/icon_hangup.svg</file>
-    <file>icons/icon_hold.svg</file>
-    <file>icons/icon_rec.svg</file>
-    <file>icons/icon_unhold.svg</file>
-    <file>icons/icon_volume_off.svg</file>
-    <file>icons/icon_volume.svg</file>
-    <file>icons/incoming.svg</file>
-    <file>icons/mailbox.svg</file>
-    <file>icons/mic_25.svg</file>
-    <file>icons/mic_50.svg</file>
-    <file>icons/mic_75.svg</file>
-    <file>icons/mic.svg</file>
-    <file>icons/missed.svg</file>
-    <file>icons/outgoing.svg</file>
-    <file>icons/rec_call.svg</file>
-    <file>icons/refuse.svg</file>
-    <file>icons/ring.svg</file>
-    <file>icons/sflphone.png</file>
-    <file>icons/speaker_25.svg</file>
-    <file>icons/speaker_50.svg</file>
-    <file>icons/speaker_75.svg</file>
-    <file>icons/speaker.svg</file>
-    <file>icons/stock_person.svg</file>
-    <file>icons/transfert.svg</file>
-    <file>icons/unhold.svg</file>
-  </qresource>
-</RCC>
diff --git a/sflphone-client-kde/Account.cpp b/sflphone-client-kde/src/Account.cpp
similarity index 77%
rename from sflphone-client-kde/Account.cpp
rename to sflphone-client-kde/src/Account.cpp
index ded51e8899f7bc18e65d01531fe18f66c40f28bf..5939416faca9bed141fe62ddfe2174bb6e9904cf 100644
--- a/sflphone-client-kde/Account.cpp
+++ b/sflphone-client-kde/src/Account.cpp
@@ -1,3 +1,24 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+
 #include "Account.h"
 
 #include <QtGui/QApplication>
@@ -31,28 +52,11 @@ const QString account_state_name(QString & s)
 
 //Constructors
 
-	Account::Account():accountId(NULL){}
-
-/*
-Account::Account(QListWidgetItem & _item, QString & alias)
-{
-	accountDetails = new MapStringString();
-	(*accountDetails)[ACCOUNT_ALIAS] = alias;
-	item = & _item;
-}
-
-Account::Account(QString & _accountId, MapStringString & _accountDetails, account_state_t & _state)
-{
-	*accountDetails = _accountDetails;
-	*accountId = _accountId;
-	*state = _state;
-}
-*/
+Account::Account():accountId(NULL){}
 
 
 void Account::initAccountItem()
 {
-	//ConfigurationManagerInterface & configurationManager = ConfigurationManagerInterfaceSingleton::getInstance();
 	item = new QListWidgetItem();
 	item->setSizeHint(QSize(140,25));
 	item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsDragEnabled|Qt::ItemIsDropEnabled|Qt::ItemIsEnabled);
diff --git a/sflphone-client-kde/src/Account.h b/sflphone-client-kde/src/Account.h
new file mode 100644
index 0000000000000000000000000000000000000000..a31c9a2ba671a0157803cf9a8ece86f244852e8c
--- /dev/null
+++ b/sflphone-client-kde/src/Account.h
@@ -0,0 +1,83 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+
+#ifndef ACCOUNT_H
+#define ACCOUNT_H
+
+#include <QtCore/QString>
+#include <QtGui/QListWidgetItem>
+#include <QtGui/QColor>
+
+// #include "metatypes.h"
+#include "AccountItemWidget.h"
+
+typedef QMap<QString, QString> MapStringString;
+
+const QString account_state_name(QString & s);
+
+class Account{
+	
+private:
+
+	QString * accountId;
+	MapStringString * accountDetails;
+	QListWidgetItem * item;
+	AccountItemWidget * itemWidget;
+
+	Account();
+
+public:
+	
+	~Account();
+	
+	//Constructors
+	static Account * buildExistingAccountFromId(QString _accountId);
+	static Account * buildNewAccountFromAlias(QString alias);
+	
+	//Getters
+	bool isNew() const;
+	bool isChecked() const;
+	QString & getAccountId();
+	MapStringString & getAccountDetails() const;
+	QListWidgetItem * getItem();
+	QListWidgetItem * renewItem();
+	AccountItemWidget * getItemWidget();
+	QString getStateName(QString & state);
+	QColor getStateColor();
+	QString getStateColorName();
+	QString getAccountDetail(QString param) const;
+	QString getAlias();
+	
+	//Setters
+	void initAccountItem();
+	void setAccountId(QString id);
+	void setAccountDetails(MapStringString m);
+	void setAccountDetail(QString param, QString val);
+	
+	//Operators
+	bool operator==(const Account&)const;
+	
+	
+};
+
+
+
+#endif
\ No newline at end of file
diff --git a/sflphone-client-kde/AccountItemWidget.cpp b/sflphone-client-kde/src/AccountItemWidget.cpp
similarity index 98%
rename from sflphone-client-kde/AccountItemWidget.cpp
rename to sflphone-client-kde/src/AccountItemWidget.cpp
index 9c437e95b3c15d254083d5f71dc7fc6ad01b8d52..eb4beda0638cf8a6e17887b409c06ce0f2b18e3b 100644
--- a/sflphone-client-kde/AccountItemWidget.cpp
+++ b/sflphone-client-kde/src/AccountItemWidget.cpp
@@ -18,6 +18,7 @@
  *   Free Software Foundation, Inc.,                                       *
  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
  ***************************************************************************/
+ 
 #include "AccountItemWidget.h"
 
 #include <QtGui/QHBoxLayout>
@@ -49,6 +50,9 @@ AccountItemWidget::AccountItemWidget(QWidget *parent)
 
 AccountItemWidget::~AccountItemWidget()
 {
+	delete led;
+	delete checkBox;
+	delete textLabel;
 }
 
 
diff --git a/sflphone-client-kde/AccountItemWidget.h b/sflphone-client-kde/src/AccountItemWidget.h
similarity index 97%
rename from sflphone-client-kde/AccountItemWidget.h
rename to sflphone-client-kde/src/AccountItemWidget.h
index 1448d0e2bddba9082b6f6aad94fcf73602f91107..7d26ccd616ba398578038849033f954d268cc790 100644
--- a/sflphone-client-kde/AccountItemWidget.h
+++ b/sflphone-client-kde/src/AccountItemWidget.h
@@ -18,6 +18,7 @@
  *   Free Software Foundation, Inc.,                                       *
  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
  ***************************************************************************/
+ 
 #ifndef ACCOUNTITEMWIDGET_H
 #define ACCOUNTITEMWIDGET_H
 
@@ -45,25 +46,24 @@ public:
 
 	enum State {Registered, Unregistered, NotWorking};
 
+	//Constructors & Destructors
 	AccountItemWidget(QWidget *parent = 0);
-
 	~AccountItemWidget();
-    
+
+	//Getters
+	int getState();
+	bool getEnabled();
+	
+	//Setters
 	void setState(int state);
-    
 	void setEnabled(bool enabled);
-	
 	void setAccountText(QString text);
 	
+	//Updates
 	void updateStateDisplay();
-	
 	void updateEnabledDisplay();
-	
 	void updateDisplay();
 	
-	int getState();
-	
-	bool getEnabled();
 	
 
 };
diff --git a/sflphone-client-kde/AccountList.cpp b/sflphone-client-kde/src/AccountList.cpp
similarity index 63%
rename from sflphone-client-kde/AccountList.cpp
rename to sflphone-client-kde/src/AccountList.cpp
index e9153cd91442a1cdf1675e2c7716cecf5c6627db..f40b7d8ad12ec9ba72448291637c4e4ef9ef8597 100644
--- a/sflphone-client-kde/AccountList.cpp
+++ b/sflphone-client-kde/src/AccountList.cpp
@@ -1,3 +1,24 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+
 #include "AccountList.h"
 #include "sflphone_const.h"
 #include "configurationmanager_interface_singleton.h"
@@ -44,6 +65,41 @@ void AccountList::update()
 	}
 }
 
+void AccountList::upAccount(int index)
+{
+	if(index <= 0 || index >= size())
+	{
+		qDebug() << "Error : index or future index out of range in upAccount.";
+		return;
+	}
+	Account & account = getAccount(index);
+	accounts->remove(index);
+	accounts->insert(index - 1, & account);
+}
+
+void AccountList::downAccount(int index)
+{
+	if(index < 0 || index >= size() - 1)
+	{
+		qDebug() << "Error : index or future index out of range in upAccount.";
+		return;
+	}
+	Account & account = getAccount(index);
+	accounts->remove(index);
+	accounts->insert(index + 1, & account);
+}
+
+
+QString AccountList::getOrderedList()
+{
+	QString order;
+	for( int i = 0 ; i < size() ; i++)
+	{
+		order += getAccount(i).getAccountId() + "/";
+	}
+	return order;
+}
+
 QVector<Account *> AccountList::registeredAccounts() const
 {
 	qDebug() << "registeredAccounts";
@@ -94,6 +150,16 @@ QVector<Account *> & AccountList::getAccounts()
 	return *accounts;
 }
 
+const Account & AccountList::getAccount (int i) const
+{
+	return *((*accounts)[i]);
+}
+
+Account & AccountList::getAccount (int i)
+{
+	return *((*accounts)[i]);
+}
+
 Account * AccountList::getAccountById(const QString & id) const
 {
 	for (int i = 0; i < accounts->size(); ++i)
@@ -114,7 +180,6 @@ QVector<Account *> AccountList::getAccountByState(QString & state)
 			v += (*accounts)[i];
 	}
 	return v;
-
 }
 /*
 Account AccountList::getAccountByRow(int row)
diff --git a/sflphone-client-kde/src/AccountList.h b/sflphone-client-kde/src/AccountList.h
new file mode 100644
index 0000000000000000000000000000000000000000..e7250b39e32942f1d685c8043c5844e0095af787
--- /dev/null
+++ b/sflphone-client-kde/src/AccountList.h
@@ -0,0 +1,71 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+
+#ifndef ACCOUNT_LIST_H
+#define ACCOUNT_LIST_H
+
+
+#include <QtCore/QVector>
+
+#include "Account.h"
+
+class AccountList{
+	
+private:
+
+	QVector<Account *> * accounts;
+	static QString firstAccount;
+
+public:
+
+	//Constructors & Destructors
+	AccountList(QStringList & _accountIds);
+	AccountList();
+	~AccountList();
+	
+	//Getters
+	QVector<Account *> & getAccounts();
+	Account & getAccount (int i);
+	const Account & getAccount (int i) const;
+	Account * getAccountById(const QString & id) const;
+	QVector<Account *>  getAccountByState(QString & state);
+	Account * getAccountByItem(QListWidgetItem * item);
+	int size();
+	Account * firstRegisteredAccount() const;
+	QString getOrderedList();
+	
+	//Setters
+	Account * addAccount(QString & alias);
+	void removeAccount(Account * account);
+	void removeAccount(QListWidgetItem * item);
+	void setAccountFirst(Account * account);
+	void upAccount(int index);
+	void downAccount(int index);
+
+	//Operators
+	Account & operator[] (int i);
+	const Account & operator[] (int i) const;
+	QVector<Account *> registeredAccounts() const;
+	void update();
+};
+
+
+#endif
\ No newline at end of file
diff --git a/sflphone-client-kde/AccountWizard.cpp b/sflphone-client-kde/src/AccountWizard.cpp
similarity index 99%
rename from sflphone-client-kde/AccountWizard.cpp
rename to sflphone-client-kde/src/AccountWizard.cpp
index 832a3b54b62ed3b1ddd9aa25b8c1928a266dc6ec..4745593e5e1e28554f173d2750b8bb92e75612ef 100644
--- a/sflphone-client-kde/AccountWizard.cpp
+++ b/sflphone-client-kde/src/AccountWizard.cpp
@@ -148,7 +148,6 @@ rest_account get_rest_account(char *host,char *email) {
 AccountWizard::AccountWizard(QWidget * parent)
  : QWizard(parent)
 {
-	
 	setPage(Page_Intro, new WizardIntroPage);
 	setPage(Page_AutoMan, new WizardAccountAutoManualPage);
 	setPage(Page_Type, new WizardAccountTypePage);
@@ -159,10 +158,8 @@ AccountWizard::AccountWizard(QWidget * parent)
 	setPage(Page_Conclusion, new WizardAccountConclusionPage);
 	
 	setStartId(Page_Intro);
-	//setPixmap(QWizard::BannerPixmap, QPixmap(":/images/icons/dial.svg"));
 	setWindowTitle(tr2i18n("Account Wizard"));
 	setPixmap(QWizard::LogoPixmap, QPixmap(":/images/icons/sflphone.png"));
-
 }
 
 
@@ -554,7 +551,6 @@ WizardAccountConclusionPage::WizardAccountConclusionPage(QWidget *parent)
 
 WizardAccountConclusionPage::~WizardAccountConclusionPage()
 {
-	//delete label_emailAddress;
 }
 
 int WizardAccountConclusionPage::nextId() const
diff --git a/sflphone-client-kde/AccountWizard.h b/sflphone-client-kde/src/AccountWizard.h
similarity index 98%
rename from sflphone-client-kde/AccountWizard.h
rename to sflphone-client-kde/src/AccountWizard.h
index 625c8c627717173172435deb72bad260dbfc4724..0095856a18c523178e31eb77d9e1c1c863ddc1f0 100644
--- a/sflphone-client-kde/AccountWizard.h
+++ b/sflphone-client-kde/src/AccountWizard.h
@@ -185,8 +185,6 @@ public:
 	int nextId() const;
 
 private:
-	//QLabel * label_emailAddress;
-	//QLineEdit * lineEdit_emailAddress;
 };
 
 #endif
diff --git a/sflphone-client-kde/ActionSetAccountFirst.cpp b/sflphone-client-kde/src/ActionSetAccountFirst.cpp
similarity index 99%
rename from sflphone-client-kde/ActionSetAccountFirst.cpp
rename to sflphone-client-kde/src/ActionSetAccountFirst.cpp
index bef7dbc8cd01fcf2bffd74d0537f804ae1c88e23..6b29e6c6a4892502e68580ddcf7d52ca94996dc1 100644
--- a/sflphone-client-kde/ActionSetAccountFirst.cpp
+++ b/sflphone-client-kde/src/ActionSetAccountFirst.cpp
@@ -18,6 +18,7 @@
  *   Free Software Foundation, Inc.,                                       *
  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
  ***************************************************************************/
+  
 #include "ActionSetAccountFirst.h"
 
 ActionSetAccountFirst::ActionSetAccountFirst(Account * account, QObject *parent)
diff --git a/sflphone-client-kde/ActionSetAccountFirst.h b/sflphone-client-kde/src/ActionSetAccountFirst.h
similarity index 99%
rename from sflphone-client-kde/ActionSetAccountFirst.h
rename to sflphone-client-kde/src/ActionSetAccountFirst.h
index 6d53166ff574cce5e0b14412a1e43860ca3e33b7..dd8914f474aaf5ec01e63ff064f3213f31756ded 100644
--- a/sflphone-client-kde/ActionSetAccountFirst.h
+++ b/sflphone-client-kde/src/ActionSetAccountFirst.h
@@ -18,6 +18,7 @@
  *   Free Software Foundation, Inc.,                                       *
  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
  ***************************************************************************/
+ 
 #ifndef ACTION_SET_ACCOUNT_FIRST_H
 #define ACTION_SET_ACCOUNT_FIRST_H
 
@@ -33,10 +34,12 @@ class ActionSetAccountFirst : public QAction
 Q_OBJECT
 
 private:
+	
 	Account * account;
+
 public:
-	ActionSetAccountFirst(Account * account, QObject *parent = 0);
 
+	ActionSetAccountFirst(Account * account, QObject *parent = 0);
 	~ActionSetAccountFirst();
 
 private slots:
diff --git a/sflphone-client-kde/src/CMakeLists.txt b/sflphone-client-kde/src/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5762b2bb0708d223b02ad9978ea62cca129e25da
--- /dev/null
+++ b/sflphone-client-kde/src/CMakeLists.txt
@@ -0,0 +1,96 @@
+
+ADD_DEFINITIONS(${KDE4_DEFINITIONS} ${QT_DEFINITIONS} -fexceptions -DDATA_INSTALL_DIR="\\\"${DATA_INSTALL_DIR}\\\"" )
+
+SET ( KDE4_KABC_LIBS  -lkabc )
+
+
+
+
+
+SET(
+	sflphone_client_kde_SRCS
+	sflphone_kdeview.cpp
+	SFLPhone.cpp
+	ConfigDialog.cpp
+	main.cpp
+	sflphone_const.h
+	Account.cpp
+	AccountList.cpp
+	Call.cpp
+	CallList.cpp
+	configurationmanager_interface_singleton.cpp
+	callmanager_interface_singleton.cpp
+	instance_interface_singleton.cpp
+	AccountWizard.cpp
+	AccountItemWidget.cpp
+	ActionSetAccountFirst.cpp
+	Contact.cpp
+	ContactItemWidget.cpp
+)
+ 
+
+# generate rules for building source files from the resources
+SET(QtApp_RCCS qrc/resources.qrc)
+QT4_ADD_RESOURCES(QtApp_RCC_SRCS ${QtApp_RCCS})
+
+
+# Build dbus interfaces
+SET ( dbus_xml_introspecs_path ${CMAKE_CURRENT_SOURCE_DIR}/../../sflphone-common/src/dbus/)
+
+# configuration manager interface
+SET ( configurationmanager_xml  ${dbus_xml_introspecs_path}/configurationmanager-introspec.xml )
+
+SET_SOURCE_FILES_PROPERTIES(
+   ${configurationmanager_xml}
+   PROPERTIES 
+   CLASSNAME ConfigurationManagerInterface
+   INCLUDE "dbus/metatypes.h") 
+
+QT4_ADD_DBUS_INTERFACE(
+   sflphone_client_kde_SRCS 
+   ${configurationmanager_xml}
+   configurationmanager_dbus_interface)
+
+# call manager interface
+SET ( callmanager_xml  ${dbus_xml_introspecs_path}/callmanager-introspec.xml )
+
+SET_SOURCE_FILES_PROPERTIES(
+   ${callmanager_xml}
+   PROPERTIES 
+   CLASSNAME CallManagerInterface
+   INCLUDE "dbus/metatypes.h") 
+
+QT4_ADD_DBUS_INTERFACE(
+   sflphone_client_kde_SRCS 
+   ${callmanager_xml}
+   callmanager_dbus_interface)
+
+# instance interface
+SET ( instance_xml  ${dbus_xml_introspecs_path}/instance-introspec.xml )
+
+SET_SOURCE_FILES_PROPERTIES(
+   ${instance_xml}
+   PROPERTIES 
+   CLASSNAME InstanceInterface
+   INCLUDE "dbus/metatypes.h") 
+   
+QT4_ADD_DBUS_INTERFACE(
+   sflphone_client_kde_SRCS 
+   ${instance_xml}
+   instance_dbus_interface)
+
+
+# kde4_automoc(${sflphone_client_kde_SRCS})
+
+KDE4_ADD_UI_FILES(sflphone_client_kde_SRCS ui/sflphone_kdeview_base.ui ui/ConfigDialog.ui)
+
+KDE4_ADD_EXECUTABLE(sflphone-client-kde ${sflphone_client_kde_SRCS} ${QtApp_RCC_SRCS})
+
+TARGET_LINK_LIBRARIES(sflphone-client-kde ${KDE4_KDEUI_LIBS} ${KDE4_KIO_LIBS} ${KDE4_KABC_LIBS})
+
+
+########### install files ###############
+
+INSTALL(TARGETS sflphone-client-kde DESTINATION ${BIN_INSTALL_DIR})
+
+
diff --git a/sflphone-client-kde/Call.cpp b/sflphone-client-kde/src/Call.cpp
similarity index 93%
rename from sflphone-client-kde/Call.cpp
rename to sflphone-client-kde/src/Call.cpp
index a9dde32c2676553cdb22d194c137d9eead66a01f..d7aacb29495b2aff59c5890e6aa3073bc306ae55 100644
--- a/sflphone-client-kde/Call.cpp
+++ b/sflphone-client-kde/src/Call.cpp
@@ -1,3 +1,23 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
 #include "Call.h"
 
 #include "callmanager_interface_singleton.h"
@@ -181,6 +201,7 @@ Call * Call::buildIncomingCall(const QString & callId/*, const QString & from, c
 {
 	CallManagerInterface & callManager = CallManagerInterfaceSingleton::getInstance();
 	MapStringString details = callManager.getCallDetails(callId).value();
+	qDebug() << "details = " << details;
 	QString from = details[CALL_PEER_NUMBER];
 	QString account = details[CALL_ACCOUNTID];
 	QString peerName = details[CALL_PEER_NAME];
diff --git a/sflphone-client-kde/Call.h b/sflphone-client-kde/src/Call.h
similarity index 74%
rename from sflphone-client-kde/Call.h
rename to sflphone-client-kde/src/Call.h
index 2123264e6d8be040cbe453553487e46daccb9994..9d2bea58a34fbd32837ba266ae78fae3c463396c 100644
--- a/sflphone-client-kde/Call.h
+++ b/sflphone-client-kde/src/Call.h
@@ -1,3 +1,25 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+
+
 #ifndef CALL_H
 #define CALL_H
 
@@ -157,13 +179,15 @@ private:
 
 public:
 	
+	//Constructors & Destructors
 	~Call();
 	void initCallItem();
 	static Call * buildDialingCall(QString callId, const QString & peerName);
 	static Call * buildIncomingCall(const QString & callId/*, const QString & from, const QString & account*/);
 	static Call * buildRingingCall(const QString & callId);
-	Contact * findContactForNumberInKAddressBook(QString number);
 	
+	
+	//Getters
 	QListWidgetItem * getItem();
 	QWidget * getItemWidget();
 	QListWidgetItem * getHistoryItem();
@@ -172,19 +196,26 @@ public:
 	QString getCallId() const;
 	QString getPeerPhoneNumber() const;
 	QString getPeerName() const;
-	
-	call_state stateChanged(const QString & newState);
-	call_state actionPerformed(call_action action);
 	call_state getCurrentState() const;
 	history_state getHistoryState() const;
 	bool getRecording() const;
+	
+	//Automate calls
+	call_state stateChanged(const QString & newState);
+	call_state actionPerformed(call_action action);
+	
+	//Setters
 	void appendItemText(QString text);
 	void backspaceItemText();
 	void setItemIcon(const QString pixmap);
 // 	void setPeerName(const QString peerName);
 	void changeCurrentState(call_state newState);
+	
+	//Updates
 	void updateItem();
 
+	//Utils
+	Contact * findContactForNumberInKAddressBook(QString number);
 
 };
 
diff --git a/sflphone-client-kde/CallList.cpp b/sflphone-client-kde/src/CallList.cpp
similarity index 55%
rename from sflphone-client-kde/CallList.cpp
rename to sflphone-client-kde/src/CallList.cpp
index eff568961712f3454a7145e71c9e6f59b4e78ffc..3ee4851c2ee2a4d2b59fb0fb044544f79e69f3bc 100644
--- a/sflphone-client-kde/CallList.cpp
+++ b/sflphone-client-kde/src/CallList.cpp
@@ -1,3 +1,24 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/ 
+
 #include "CallList.h"
 
 CallList::CallList()
diff --git a/sflphone-client-kde/src/CallList.h b/sflphone-client-kde/src/CallList.h
new file mode 100644
index 0000000000000000000000000000000000000000..9333abd03775479a7fa14e475039a5e66c7da81e
--- /dev/null
+++ b/sflphone-client-kde/src/CallList.h
@@ -0,0 +1,66 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/ 
+
+#ifndef CALL_LIST_H
+#define CALL_LIST_H
+
+#include <QtCore/QVector>
+#include <QtCore/QString>
+#include <QtGui/QListWidgetItem>
+
+#include "Call.h"
+
+class CallList
+{
+private:
+
+	QVector<Call *> * calls;
+	int callIdCpt;
+
+public:
+
+	//Constructors & Destructors
+	CallList();
+	~CallList();
+
+	//Getters
+	Call * findCallByItem(const QListWidgetItem * item);
+	Call * findCallByHistoryItem(const QListWidgetItem * item);
+	Call * findCallByCallId(const QString & callId);
+	Call * operator[](const QListWidgetItem * item);
+	Call * operator[](const QString & callId);
+	Call * operator[](int ind);
+	int size();
+
+	//Setters
+	Call * addDialingCall(const QString & peerName = "");
+	Call * addIncomingCall(const QString & callId/*, const QString & from, const QString & account*/);
+	Call * addRingingCall(const QString & callId);
+
+	//GSetter
+	QString getAndIncCallId();
+	
+
+
+};
+
+
+#endif
\ No newline at end of file
diff --git a/sflphone-client-kde/ConfigDialog.cpp b/sflphone-client-kde/src/ConfigDialog.cpp
similarity index 93%
rename from sflphone-client-kde/ConfigDialog.cpp
rename to sflphone-client-kde/src/ConfigDialog.cpp
index a6f6677ef04a94d5018c76155e490f4bd35935fd..2e340c73fdc4e35bdffc9ca0d2e2b7534deefaca 100644
--- a/sflphone-client-kde/ConfigDialog.cpp
+++ b/sflphone-client-kde/src/ConfigDialog.cpp
@@ -1,4 +1,25 @@
-#include "ConfigDialog.h"
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+ 
+ #include "ConfigDialog.h"
 
 #include <QtGui/QStyle>
 #include <QErrorMessage>
@@ -9,9 +30,11 @@
 
 
 #include "sflphone_const.h"
-#include "metatypes.h"
+// #include "metatypes.h"
 #include "configurationmanager_interface_singleton.h"
 
+typedef QMap<QString, QString> MapStringString;
+typedef QMap<QString, int> MapStringInt;
 
 AccountList * ConfigurationDialog::accountList;
 
@@ -363,6 +386,7 @@ void ConfigurationDialog::loadAccountList()
 		frame2_editAccounts->setEnabled(false);
 }
 
+
 void ConfigurationDialog::saveAccountList()
 {
 	//get the configurationManager instance
@@ -408,6 +432,7 @@ void ConfigurationDialog::saveAccountList()
 			configurationManager.removeAccount(accountIds[i]);
 		}
 	}
+	configurationManager.setAccountsOrder(accountList->getOrderedList());
 }
 
 void ConfigurationDialog::loadAccount(QListWidgetItem * item)
@@ -649,6 +674,7 @@ void ConfigurationDialog::on_button_accountUp_clicked()
 	Account * account = accountList->getAccountByItem(prevItem);
 	//we need to build a new item to set the itemWidget back
 	QListWidgetItem * item = account->renewItem();
+	accountList->upAccount(currentRow);
 	delete prevItem;
 	listWidget_accountList->insertItem(currentRow - 1 , item);
 	listWidget_accountList->setItemWidget(item, account->getItemWidget());
@@ -661,6 +687,7 @@ void ConfigurationDialog::on_button_accountDown_clicked()
 	QListWidgetItem * prevItem = listWidget_accountList->takeItem(currentRow);
 	Account * account = accountList->getAccountByItem(prevItem);
 	QListWidgetItem * item = account->renewItem();
+	accountList->downAccount(currentRow);
 	delete prevItem;
 	listWidget_accountList->insertItem(currentRow + 1 , item);
 	listWidget_accountList->setItemWidget(item, account->getItemWidget());
diff --git a/sflphone-client-kde/ConfigDialog.h b/sflphone-client-kde/src/ConfigDialog.h
similarity index 53%
rename from sflphone-client-kde/ConfigDialog.h
rename to sflphone-client-kde/src/ConfigDialog.h
index 42f51341ec921dbaaeb14e4b27e6728d37aaa061..241ec75106d286e477cc99abb31e85aee76ed3e2 100644
--- a/sflphone-client-kde/ConfigDialog.h
+++ b/sflphone-client-kde/src/ConfigDialog.h
@@ -1,3 +1,24 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+ 
 #ifndef HEADER_CONFIGDIALOG
 #define HEADER_CONFIGDIALOG
 
@@ -25,26 +46,31 @@ private:
 	
 
 public:
+
+	//Constructors & Destructors
 	ConfigurationDialog(sflphone_kdeView *parent = 0);
 	~ConfigurationDialog();
+	
+	//Getters
 	static AccountList * getAccountList();
 
+	//Setters
+	void setPage(int page);
+	void addAccountToAccountList(Account * account);
+	
 	void loadAccount(QListWidgetItem * item);
 	void saveAccount(QListWidgetItem * item);
 
 	void loadAccountList();
 	void saveAccountList();
 	
-	void addAccountToAccountList(Account * account);
-
 	void loadCodecs();
 	void saveCodecs();
 
 	void loadOptions();
 	void saveOptions();
 	
-	void setPage(int page);
-	
+	//Updates
 	void updateCodecListCommands();
 	void updateAccountListCommands();
 
@@ -68,7 +94,6 @@ private slots:
 	void on1_parametersChanged();
 	void on1_errorAlert(int code);
 	
-
 };
 
 #endif 
diff --git a/sflphone-client-kde/Contact.cpp b/sflphone-client-kde/src/Contact.cpp
similarity index 98%
rename from sflphone-client-kde/Contact.cpp
rename to sflphone-client-kde/src/Contact.cpp
index 3929e609e3e0b56e841731f5b29aa3506f463b37..60d32f21a85e7232ac29269f0578b54b70588665 100644
--- a/sflphone-client-kde/Contact.cpp
+++ b/sflphone-client-kde/src/Contact.cpp
@@ -48,6 +48,9 @@ Contact::Contact(Addressee addressee, const PhoneNumber & number, bool displayPh
 
 Contact::~Contact()
 {
+	delete item;
+	delete itemWidget;
+	delete photo;
 }
 
 void Contact::initItem(bool displayPhoto)
diff --git a/sflphone-client-kde/Contact.h b/sflphone-client-kde/src/Contact.h
similarity index 84%
rename from sflphone-client-kde/Contact.h
rename to sflphone-client-kde/src/Contact.h
index 5fb25e526f71954f15ea8938cca1566aa9c9d58e..0d62657eab85f15e4ad24c9be9d7f0e9dd3d5483 100644
--- a/sflphone-client-kde/Contact.h
+++ b/sflphone-client-kde/src/Contact.h
@@ -48,20 +48,20 @@ private:
 	void initItem(bool displayPhoto);
 
 public:
-    Contact(Addressee addressee, const PhoneNumber & number, bool displayPhoto);
 
-    ~Contact();
-    
-    QString getPhoneNumber() const;
-    QString getNickName() const;
-    QString getFirstName() const;
-    QString getSecondName() const;
-    const Picture * getPhoto() const;
-    PhoneNumber::Type getType() const;
-    
-    QListWidgetItem * getItem();
-    
-    QWidget * getItemWidget();
+	//Constructors & Destructors
+	Contact(Addressee addressee, const PhoneNumber & number, bool displayPhoto);
+	~Contact();
+	
+	//Getters
+	QString getPhoneNumber() const;
+	QString getNickName() const;
+	QString getFirstName() const;
+	QString getSecondName() const;
+	const Picture * getPhoto() const;
+	PhoneNumber::Type getType() const;
+	QListWidgetItem * getItem();
+	QWidget * getItemWidget();
 
 };
 
diff --git a/sflphone-client-kde/ContactItemWidget.cpp b/sflphone-client-kde/src/ContactItemWidget.cpp
similarity index 97%
rename from sflphone-client-kde/ContactItemWidget.cpp
rename to sflphone-client-kde/src/ContactItemWidget.cpp
index 7c634481a43ce2f2e5fa4df57b8b8913f5e865ed..f32614c58dc753e3053516d5ec5755ba45cade85 100644
--- a/sflphone-client-kde/ContactItemWidget.cpp
+++ b/sflphone-client-kde/src/ContactItemWidget.cpp
@@ -88,6 +88,10 @@ ContactItemWidget::ContactItemWidget(const Contact * contact, bool displayPhoto,
 
 ContactItemWidget::~ContactItemWidget()
 {
+	delete contactName;
+	delete contactNumber;
+// 	delete contactPhoto;
+	delete contactType;
 }
 
 
diff --git a/sflphone-client-kde/ContactItemWidget.h b/sflphone-client-kde/src/ContactItemWidget.h
similarity index 98%
rename from sflphone-client-kde/ContactItemWidget.h
rename to sflphone-client-kde/src/ContactItemWidget.h
index dd686bd0bbf42c57c8773f701acea5a8d4c07d97..491af56d961266b0a210c4edab5d23ad0f7341ed 100644
--- a/sflphone-client-kde/ContactItemWidget.h
+++ b/sflphone-client-kde/src/ContactItemWidget.h
@@ -39,10 +39,12 @@ private:
 	QLabel * contactType;
 	
 public:
-	ContactItemWidget(const Contact * contact, bool displayPhoto, QWidget *parent = 0);
 
+	//Constructors & Destructors
+	ContactItemWidget(const Contact * contact, bool displayPhoto, QWidget *parent = 0);
 	~ContactItemWidget();
 	
+	//Getters
 	QString getContactName();
 	QString getContactNumber();
 
diff --git a/sflphone-client-kde/SFLPhone.cpp b/sflphone-client-kde/src/SFLPhone.cpp
similarity index 77%
rename from sflphone-client-kde/SFLPhone.cpp
rename to sflphone-client-kde/src/SFLPhone.cpp
index 37ac52291bc21a3c0eb6b8259d1ed1fcbd4828c7..9e6955837a3abb364887b2e2ae020af96a2c20ae 100644
--- a/sflphone-client-kde/SFLPhone.cpp
+++ b/sflphone-client-kde/src/SFLPhone.cpp
@@ -1,3 +1,24 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+ 
 #include "SFLPhone.h"
 
 #include <KApplication>
diff --git a/sflphone-client-kde/src/SFLPhone.h b/sflphone-client-kde/src/SFLPhone.h
new file mode 100644
index 0000000000000000000000000000000000000000..7b8edd3c21d0e3aa5cc9400c07e4454f4d682f24
--- /dev/null
+++ b/sflphone-client-kde/src/SFLPhone.h
@@ -0,0 +1,77 @@
+/***************************************************************************
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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.,                                       *
+ *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ ***************************************************************************/
+
+#ifndef SFLPHONE_H
+#define SFLPHONE_H
+
+#include <QtCore/QString>
+#include <QtCore/QVector>
+#include <QtGui/QListWidgetItem>
+#include <QtGui/QKeyEvent>
+#include <QErrorMessage>
+#include <QSystemTrayIcon>
+
+#include <KXmlGuiWindow>
+
+#include "ui_sflphone_kdeview_base.h"
+#include "ConfigDialog.h"
+#include "CallList.h"
+#include "AccountWizard.h"
+#include "Contact.h"
+#include "sflphone_kdeview.h"
+
+
+class ConfigurationDialog;
+class sflphone_kdeView;
+
+class SFLPhone : public KXmlGuiWindow
+{
+
+Q_OBJECT
+
+private:
+	sflphone_kdeView * view;
+	QMenu *trayIconMenu;
+	bool iconChanged;
+	QSystemTrayIcon *trayIcon;
+
+protected:
+	virtual bool queryClose();
+	virtual void changeEvent(QEvent * event);
+
+public:
+	SFLPhone(QWidget *parent = 0);
+	~SFLPhone();
+	void setupActions();
+	void sendNotif(QString caller);
+	void putForeground();
+	void trayIconSignal();
+	
+	
+private slots:
+	void on_trayIcon_activated(QSystemTrayIcon::ActivationReason reason);
+	void on_trayIcon_messageClicked();
+
+
+};
+
+#endif
+ 
diff --git a/sflphone-client-kde/callmanager_interface_singleton.cpp b/sflphone-client-kde/src/callmanager_interface_singleton.cpp
similarity index 100%
rename from sflphone-client-kde/callmanager_interface_singleton.cpp
rename to sflphone-client-kde/src/callmanager_interface_singleton.cpp
diff --git a/sflphone-client-kde/callmanager_interface_singleton.h b/sflphone-client-kde/src/callmanager_interface_singleton.h
similarity index 100%
rename from sflphone-client-kde/callmanager_interface_singleton.h
rename to sflphone-client-kde/src/callmanager_interface_singleton.h
diff --git a/sflphone-client-kde/configurationmanager_interface_singleton.cpp b/sflphone-client-kde/src/configurationmanager_interface_singleton.cpp
similarity index 100%
rename from sflphone-client-kde/configurationmanager_interface_singleton.cpp
rename to sflphone-client-kde/src/configurationmanager_interface_singleton.cpp
diff --git a/sflphone-client-kde/configurationmanager_interface_singleton.h b/sflphone-client-kde/src/configurationmanager_interface_singleton.h
similarity index 100%
rename from sflphone-client-kde/configurationmanager_interface_singleton.h
rename to sflphone-client-kde/src/configurationmanager_interface_singleton.h
diff --git a/sflphone-client-kde/src/dbus/CMakeLists.txt b/sflphone-client-kde/src/dbus/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..928a6f963043f8275a557c19ad243e68165f5c5d
--- /dev/null
+++ b/sflphone-client-kde/src/dbus/CMakeLists.txt
@@ -0,0 +1,48 @@
+
+MESSAGE("Yeeeeaaaaah : rentre dans dbus!!!!!")
+# Build dbus interfaces
+
+# configuration manager interface
+
+SET ( configurationmanager_xml  ${CMAKE_CURRENT_SOURCE_DIR}/../sflphone-common/src/dbus/configurationmanager-introspec.xml )
+
+SET_SOURCE_FILES_PROPERTIES(
+   ${configurationmanager_xml}
+   PROPERTIES 
+   CLASSNAME ConfigurationManagerInterface
+   INCLUDE "metatypes.h") 
+
+QT4_ADD_DBUS_INTERFACE(
+   sflphone_client_kde_SRCS 
+   ${configurationmanager_xml}
+   configurationmanager_dbus_interface)
+
+# call manager interface
+
+SET ( callmanager_xml  ${CMAKE_CURRENT_SOURCE_DIR}/../sflphone-common/src/dbus/callmanager-introspec.xml )
+
+SET_SOURCE_FILES_PROPERTIES(
+   ${callmanager_xml}
+   PROPERTIES 
+   CLASSNAME CallManagerInterface
+   INCLUDE "metatypes.h") 
+
+QT4_ADD_DBUS_INTERFACE(
+   sflphone_client_kde_SRCS 
+   ${callmanager_xml}
+   callmanager_dbus_interface)
+
+# instance interface
+
+SET ( instance_xml  ${CMAKE_CURRENT_SOURCE_DIR}/../sflphone-common/src/dbus/instance-introspec.xml )
+
+SET_SOURCE_FILES_PROPERTIES(
+   ${instance_xml}
+   PROPERTIES 
+   CLASSNAME InstanceInterface
+   INCLUDE "metatypes.h") 
+   
+QT4_ADD_DBUS_INTERFACE(
+   sflphone_client_kde_SRCS 
+   ${instance_xml}
+   instance_dbus_interface)
diff --git a/sflphone-client-kde/metatypes.h b/sflphone-client-kde/src/dbus/metatypes.h
similarity index 68%
rename from sflphone-client-kde/metatypes.h
rename to sflphone-client-kde/src/dbus/metatypes.h
index e5ae32d8fd449c7a20c28a3e93083b378047798f..a4b2499ba203d5207bc715430aba6da5d88d7dd3 100644
--- a/sflphone-client-kde/metatypes.h
+++ b/sflphone-client-kde/src/dbus/metatypes.h
@@ -1,26 +1,21 @@
 #ifndef METATYPES_H
 #define METATYPES_H
 
-#include <QtCore/QList>
 #include <QtCore/QMetaType>
 #include <QtCore/QMap>
 #include <QtCore/QString>
 #include <QtDBus/QtDBus>
 
-//class MapStringString:public QMap<QString, QString>{};
 typedef QMap<QString, QString> MapStringString;
 typedef QMap<QString, int> MapStringInt;
-//typedef QVector<QString> VectorString;
 
 Q_DECLARE_METATYPE(MapStringString)
 Q_DECLARE_METATYPE(MapStringInt)
-//Q_DECLARE_METATYPE(VectorString)
 
 
 inline void registerCommTypes() {
 	qDBusRegisterMetaType<MapStringString>();
 	qDBusRegisterMetaType<MapStringInt>();
-	//qDBusRegisterMetaType<VectorString>();
 }
 
 #endif
\ No newline at end of file
diff --git a/sflphone-client-kde/icons/accept.svg b/sflphone-client-kde/src/icons/accept.svg
similarity index 100%
rename from sflphone-client-kde/icons/accept.svg
rename to sflphone-client-kde/src/icons/accept.svg
diff --git a/sflphone-client-kde/icons/add.png b/sflphone-client-kde/src/icons/add.png
similarity index 100%
rename from sflphone-client-kde/icons/add.png
rename to sflphone-client-kde/src/icons/add.png
diff --git a/sflphone-client-kde/icons/application-exit.png b/sflphone-client-kde/src/icons/application-exit.png
similarity index 100%
rename from sflphone-client-kde/icons/application-exit.png
rename to sflphone-client-kde/src/icons/application-exit.png
diff --git a/sflphone-client-kde/icons/busy.svg b/sflphone-client-kde/src/icons/busy.svg
similarity index 100%
rename from sflphone-client-kde/icons/busy.svg
rename to sflphone-client-kde/src/icons/busy.svg
diff --git a/sflphone-client-kde/icons/call.svg b/sflphone-client-kde/src/icons/call.svg
similarity index 100%
rename from sflphone-client-kde/icons/call.svg
rename to sflphone-client-kde/src/icons/call.svg
diff --git a/sflphone-client-kde/icons/current.svg b/sflphone-client-kde/src/icons/current.svg
similarity index 100%
rename from sflphone-client-kde/icons/current.svg
rename to sflphone-client-kde/src/icons/current.svg
diff --git a/sflphone-client-kde/icons/del_off.png b/sflphone-client-kde/src/icons/del_off.png
similarity index 100%
rename from sflphone-client-kde/icons/del_off.png
rename to sflphone-client-kde/src/icons/del_off.png
diff --git a/sflphone-client-kde/icons/del_on.png b/sflphone-client-kde/src/icons/del_on.png
similarity index 100%
rename from sflphone-client-kde/icons/del_on.png
rename to sflphone-client-kde/src/icons/del_on.png
diff --git a/sflphone-client-kde/icons/dial.svg b/sflphone-client-kde/src/icons/dial.svg
similarity index 100%
rename from sflphone-client-kde/icons/dial.svg
rename to sflphone-client-kde/src/icons/dial.svg
diff --git a/sflphone-client-kde/icons/fail.svg b/sflphone-client-kde/src/icons/fail.svg
similarity index 100%
rename from sflphone-client-kde/icons/fail.svg
rename to sflphone-client-kde/src/icons/fail.svg
diff --git a/sflphone-client-kde/icons/hang_up.svg b/sflphone-client-kde/src/icons/hang_up.svg
similarity index 100%
rename from sflphone-client-kde/icons/hang_up.svg
rename to sflphone-client-kde/src/icons/hang_up.svg
diff --git a/sflphone-client-kde/icons/history.svg b/sflphone-client-kde/src/icons/history.svg
similarity index 100%
rename from sflphone-client-kde/icons/history.svg
rename to sflphone-client-kde/src/icons/history.svg
diff --git a/sflphone-client-kde/icons/history2.svg b/sflphone-client-kde/src/icons/history2.svg
similarity index 100%
rename from sflphone-client-kde/icons/history2.svg
rename to sflphone-client-kde/src/icons/history2.svg
diff --git a/sflphone-client-kde/icons/hold.svg b/sflphone-client-kde/src/icons/hold.svg
similarity index 100%
rename from sflphone-client-kde/icons/hold.svg
rename to sflphone-client-kde/src/icons/hold.svg
diff --git a/sflphone-client-kde/icons/icon_accept.svg b/sflphone-client-kde/src/icons/icon_accept.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_accept.svg
rename to sflphone-client-kde/src/icons/icon_accept.svg
diff --git a/sflphone-client-kde/icons/icon_call.svg b/sflphone-client-kde/src/icons/icon_call.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_call.svg
rename to sflphone-client-kde/src/icons/icon_call.svg
diff --git a/sflphone-client-kde/icons/icon_dialpad.svg b/sflphone-client-kde/src/icons/icon_dialpad.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_dialpad.svg
rename to sflphone-client-kde/src/icons/icon_dialpad.svg
diff --git a/sflphone-client-kde/icons/icon_dialpad_off.svg b/sflphone-client-kde/src/icons/icon_dialpad_off.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_dialpad_off.svg
rename to sflphone-client-kde/src/icons/icon_dialpad_off.svg
diff --git a/sflphone-client-kde/icons/icon_hangup.svg b/sflphone-client-kde/src/icons/icon_hangup.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_hangup.svg
rename to sflphone-client-kde/src/icons/icon_hangup.svg
diff --git a/sflphone-client-kde/icons/icon_hold.svg b/sflphone-client-kde/src/icons/icon_hold.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_hold.svg
rename to sflphone-client-kde/src/icons/icon_hold.svg
diff --git a/sflphone-client-kde/icons/icon_rec.svg b/sflphone-client-kde/src/icons/icon_rec.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_rec.svg
rename to sflphone-client-kde/src/icons/icon_rec.svg
diff --git a/sflphone-client-kde/icons/icon_unhold.svg b/sflphone-client-kde/src/icons/icon_unhold.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_unhold.svg
rename to sflphone-client-kde/src/icons/icon_unhold.svg
diff --git a/sflphone-client-kde/icons/icon_volume.svg b/sflphone-client-kde/src/icons/icon_volume.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_volume.svg
rename to sflphone-client-kde/src/icons/icon_volume.svg
diff --git a/sflphone-client-kde/icons/icon_volume_off.svg b/sflphone-client-kde/src/icons/icon_volume_off.svg
similarity index 100%
rename from sflphone-client-kde/icons/icon_volume_off.svg
rename to sflphone-client-kde/src/icons/icon_volume_off.svg
diff --git a/sflphone-client-kde/icons/incoming.svg b/sflphone-client-kde/src/icons/incoming.svg
similarity index 100%
rename from sflphone-client-kde/icons/incoming.svg
rename to sflphone-client-kde/src/icons/incoming.svg
diff --git a/sflphone-client-kde/src/icons/led-gray.svg b/sflphone-client-kde/src/icons/led-gray.svg
new file mode 100644
index 0000000000000000000000000000000000000000..17de5519b0c9b47e996ab65c3cfe183724bb3cca
--- /dev/null
+++ b/sflphone-client-kde/src/icons/led-gray.svg
@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   width="744.09448819"
+   height="1052.3622047"
+   id="svg2"
+   sodipodi:version="0.32"
+   inkscape:version="0.46"
+   sodipodi:docname="led-gray.svg"
+   inkscape:output_extension="org.inkscape.output.svg.inkscape">
+  <defs
+     id="defs4">
+    <linearGradient
+       id="linearGradient5185">
+      <stop
+         style="stop-color:#969995;stop-opacity:1;"
+         offset="0"
+         id="stop5187" />
+      <stop
+         style="stop-color:#252525;stop-opacity:0.97647059;"
+         offset="1"
+         id="stop5189" />
+    </linearGradient>
+    <marker
+       inkscape:stockid="Arrow2Lstart"
+       orient="auto"
+       refY="0.0"
+       refX="0.0"
+       id="Arrow2Lstart"
+       style="overflow:visible">
+      <path
+         id="path3376"
+         style="font-size:12.0;fill-rule:evenodd;stroke-width:0.62500000;stroke-linejoin:round"
+         d="M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z "
+         transform="scale(1.1) translate(1,0)" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow1Sstart"
+       orient="auto"
+       refY="0.0"
+       refX="0.0"
+       id="Arrow1Sstart"
+       style="overflow:visible">
+      <path
+         id="path3370"
+         d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
+         style="fill-rule:evenodd;stroke:#000000;stroke-width:1.0pt;marker-start:none"
+         transform="scale(0.2) translate(6,0)" />
+    </marker>
+    <linearGradient
+       inkscape:collect="always"
+       id="linearGradient3165">
+      <stop
+         style="stop-color:#e16300;stop-opacity:1;"
+         offset="0"
+         id="stop3167" />
+      <stop
+         style="stop-color:#e16300;stop-opacity:0;"
+         offset="1"
+         id="stop3169" />
+    </linearGradient>
+    <inkscape:perspective
+       sodipodi:type="inkscape:persp3d"
+       inkscape:vp_x="0 : 526.18109 : 1"
+       inkscape:vp_y="0 : 1000 : 0"
+       inkscape:vp_z="744.09448 : 526.18109 : 1"
+       inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
+       id="perspective10" />
+    <radialGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3165"
+       id="radialGradient3181"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.2682705,3.3175707,-3.0169525,0.2439616,1420.6017,-661.5798)"
+       cx="277.22891"
+       cy="368.62262"
+       fx="277.22891"
+       fy="368.62262"
+       r="62.857143" />
+    <filter
+       inkscape:collect="always"
+       id="filter3351">
+      <feGaussianBlur
+         inkscape:collect="always"
+         stdDeviation="3.7100165"
+         id="feGaussianBlur3353" />
+    </filter>
+    <radialGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient5185"
+       id="radialGradient5191"
+       cx="574.9386"
+       cy="668.12408"
+       fx="574.9386"
+       fy="668.12408"
+       r="235.64999"
+       gradientTransform="matrix(-0.7572557,-0.504794,0.5925778,-0.8889426,623.74572,1505.0832)"
+       gradientUnits="userSpaceOnUse" />
+  </defs>
+  <sodipodi:namedview
+     id="base"
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1.0"
+     gridtolerance="10000"
+     guidetolerance="10"
+     objecttolerance="10"
+     inkscape:pageopacity="0.0"
+     inkscape:pageshadow="2"
+     inkscape:zoom="0.6005537"
+     inkscape:cx="67.328445"
+     inkscape:cy="526.18109"
+     inkscape:document-units="px"
+     inkscape:current-layer="layer1"
+     showgrid="false"
+     inkscape:window-width="1440"
+     inkscape:window-height="840"
+     inkscape:window-x="-5"
+     inkscape:window-y="-3" />
+  <metadata
+     id="metadata7">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <g
+     inkscape:label="Layer 1"
+     inkscape:groupmode="layer"
+     id="layer1">
+    <g
+       id="g3178" />
+    <path
+       sodipodi:type="arc"
+       style="opacity:1;fill:url(#radialGradient5191);fill-opacity:1.0;fill-rule:evenodd;stroke:#000000;stroke-width:11.30000019000000044;stroke-linecap:butt;stroke-linejoin:miter;marker-start:none;stroke-miterlimit:16.79999923999999822;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;filter:url(#filter3351)"
+       id="path3185"
+       sodipodi:cx="535.71429"
+       sodipodi:cy="680.93359"
+       sodipodi:rx="234.28572"
+       sodipodi:ry="234.28572"
+       d="M 770.00002,680.93359 A 234.28572,234.28572 0 1 1 301.42857,680.93359 A 234.28572,234.28572 0 1 1 770.00002,680.93359 z"
+       transform="translate(-156.52222,-149.8617)" />
+  </g>
+</svg>
diff --git a/sflphone-client-kde/src/icons/led-green.svg b/sflphone-client-kde/src/icons/led-green.svg
new file mode 100644
index 0000000000000000000000000000000000000000..005cf124956dcfc5d124122b144d04a811f9e0ab
--- /dev/null
+++ b/sflphone-client-kde/src/icons/led-green.svg
@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   width="744.09448819"
+   height="1052.3622047"
+   id="svg2"
+   sodipodi:version="0.32"
+   inkscape:version="0.46"
+   sodipodi:docname="led-green.svg"
+   inkscape:output_extension="org.inkscape.output.svg.inkscape">
+  <defs
+     id="defs4">
+    <linearGradient
+       id="linearGradient5185">
+      <stop
+         style="stop-color:#39f400;stop-opacity:1;"
+         offset="0"
+         id="stop5187" />
+      <stop
+         style="stop-color:#004b05;stop-opacity:0.97647059;"
+         offset="1"
+         id="stop5189" />
+    </linearGradient>
+    <marker
+       inkscape:stockid="Arrow2Lstart"
+       orient="auto"
+       refY="0.0"
+       refX="0.0"
+       id="Arrow2Lstart"
+       style="overflow:visible">
+      <path
+         id="path3376"
+         style="font-size:12.0;fill-rule:evenodd;stroke-width:0.62500000;stroke-linejoin:round"
+         d="M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z "
+         transform="scale(1.1) translate(1,0)" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow1Sstart"
+       orient="auto"
+       refY="0.0"
+       refX="0.0"
+       id="Arrow1Sstart"
+       style="overflow:visible">
+      <path
+         id="path3370"
+         d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
+         style="fill-rule:evenodd;stroke:#000000;stroke-width:1.0pt;marker-start:none"
+         transform="scale(0.2) translate(6,0)" />
+    </marker>
+    <linearGradient
+       inkscape:collect="always"
+       id="linearGradient3165">
+      <stop
+         style="stop-color:#e16300;stop-opacity:1;"
+         offset="0"
+         id="stop3167" />
+      <stop
+         style="stop-color:#e16300;stop-opacity:0;"
+         offset="1"
+         id="stop3169" />
+    </linearGradient>
+    <inkscape:perspective
+       sodipodi:type="inkscape:persp3d"
+       inkscape:vp_x="0 : 526.18109 : 1"
+       inkscape:vp_y="0 : 1000 : 0"
+       inkscape:vp_z="744.09448 : 526.18109 : 1"
+       inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
+       id="perspective10" />
+    <radialGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3165"
+       id="radialGradient3181"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.2682705,3.3175707,-3.0169525,0.2439616,1420.6017,-661.5798)"
+       cx="277.22891"
+       cy="368.62262"
+       fx="277.22891"
+       fy="368.62262"
+       r="62.857143" />
+    <filter
+       inkscape:collect="always"
+       id="filter3351">
+      <feGaussianBlur
+         inkscape:collect="always"
+         stdDeviation="3.7100165"
+         id="feGaussianBlur3353" />
+    </filter>
+    <radialGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient5185"
+       id="radialGradient5191"
+       cx="574.9386"
+       cy="668.12408"
+       fx="574.9386"
+       fy="668.12408"
+       r="235.64999"
+       gradientTransform="matrix(-0.7572557,-0.504794,0.5925778,-0.8889426,623.74572,1505.0832)"
+       gradientUnits="userSpaceOnUse" />
+  </defs>
+  <sodipodi:namedview
+     id="base"
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1.0"
+     gridtolerance="10000"
+     guidetolerance="10"
+     objecttolerance="10"
+     inkscape:pageopacity="0.0"
+     inkscape:pageshadow="2"
+     inkscape:zoom="0.6005537"
+     inkscape:cx="67.328445"
+     inkscape:cy="526.18109"
+     inkscape:document-units="px"
+     inkscape:current-layer="layer1"
+     showgrid="false"
+     inkscape:window-width="1440"
+     inkscape:window-height="840"
+     inkscape:window-x="-5"
+     inkscape:window-y="-3" />
+  <metadata
+     id="metadata7">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <g
+     inkscape:label="Layer 1"
+     inkscape:groupmode="layer"
+     id="layer1">
+    <g
+       id="g3178" />
+    <path
+       sodipodi:type="arc"
+       style="opacity:1;fill:url(#radialGradient5191);fill-opacity:1.0;fill-rule:evenodd;stroke:#000000;stroke-width:11.30000019000000044;stroke-linecap:butt;stroke-linejoin:miter;marker-start:none;stroke-miterlimit:16.79999923999999822;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;filter:url(#filter3351)"
+       id="path3185"
+       sodipodi:cx="535.71429"
+       sodipodi:cy="680.93359"
+       sodipodi:rx="234.28572"
+       sodipodi:ry="234.28572"
+       d="M 770.00002,680.93359 A 234.28572,234.28572 0 1 1 301.42857,680.93359 A 234.28572,234.28572 0 1 1 770.00002,680.93359 z"
+       transform="translate(-156.52222,-149.8617)" />
+  </g>
+</svg>
diff --git a/sflphone-client-kde/src/icons/led-red.svg b/sflphone-client-kde/src/icons/led-red.svg
new file mode 100644
index 0000000000000000000000000000000000000000..6aa39f804da88a97b9393ebb068fd3f15270542b
--- /dev/null
+++ b/sflphone-client-kde/src/icons/led-red.svg
@@ -0,0 +1,156 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   width="744.09448819"
+   height="1052.3622047"
+   id="svg2"
+   sodipodi:version="0.32"
+   inkscape:version="0.46"
+   sodipodi:docname="led-red.svg"
+   inkscape:output_extension="org.inkscape.output.svg.inkscape">
+  <defs
+     id="defs4">
+    <linearGradient
+       id="linearGradient5185">
+      <stop
+         style="stop-color:#f40800;stop-opacity:1;"
+         offset="0"
+         id="stop5187" />
+      <stop
+         style="stop-color:#6c0000;stop-opacity:0.97647059;"
+         offset="1"
+         id="stop5189" />
+    </linearGradient>
+    <marker
+       inkscape:stockid="Arrow2Lstart"
+       orient="auto"
+       refY="0.0"
+       refX="0.0"
+       id="Arrow2Lstart"
+       style="overflow:visible">
+      <path
+         id="path3376"
+         style="font-size:12.0;fill-rule:evenodd;stroke-width:0.62500000;stroke-linejoin:round"
+         d="M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z "
+         transform="scale(1.1) translate(1,0)" />
+    </marker>
+    <marker
+       inkscape:stockid="Arrow1Sstart"
+       orient="auto"
+       refY="0.0"
+       refX="0.0"
+       id="Arrow1Sstart"
+       style="overflow:visible">
+      <path
+         id="path3370"
+         d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
+         style="fill-rule:evenodd;stroke:#000000;stroke-width:1.0pt;marker-start:none"
+         transform="scale(0.2) translate(6,0)" />
+    </marker>
+    <linearGradient
+       inkscape:collect="always"
+       id="linearGradient3165">
+      <stop
+         style="stop-color:#e16300;stop-opacity:1;"
+         offset="0"
+         id="stop3167" />
+      <stop
+         style="stop-color:#e16300;stop-opacity:0;"
+         offset="1"
+         id="stop3169" />
+    </linearGradient>
+    <inkscape:perspective
+       sodipodi:type="inkscape:persp3d"
+       inkscape:vp_x="0 : 526.18109 : 1"
+       inkscape:vp_y="0 : 1000 : 0"
+       inkscape:vp_z="744.09448 : 526.18109 : 1"
+       inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
+       id="perspective10" />
+    <radialGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3165"
+       id="radialGradient3181"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="matrix(0.2682705,3.3175707,-3.0169525,0.2439616,1420.6017,-661.5798)"
+       cx="277.22891"
+       cy="368.62262"
+       fx="277.22891"
+       fy="368.62262"
+       r="62.857143" />
+    <filter
+       inkscape:collect="always"
+       id="filter3351">
+      <feGaussianBlur
+         inkscape:collect="always"
+         stdDeviation="3.7100165"
+         id="feGaussianBlur3353" />
+    </filter>
+    <radialGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient5185"
+       id="radialGradient5191"
+       cx="574.9386"
+       cy="668.12408"
+       fx="574.9386"
+       fy="668.12408"
+       r="235.64999"
+       gradientTransform="matrix(-0.7572557,-0.504794,0.5925778,-0.8889426,623.74572,1505.0832)"
+       gradientUnits="userSpaceOnUse" />
+  </defs>
+  <sodipodi:namedview
+     id="base"
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1.0"
+     gridtolerance="10000"
+     guidetolerance="10"
+     objecttolerance="10"
+     inkscape:pageopacity="0.0"
+     inkscape:pageshadow="2"
+     inkscape:zoom="0.6005537"
+     inkscape:cx="372.04724"
+     inkscape:cy="526.18109"
+     inkscape:document-units="px"
+     inkscape:current-layer="layer1"
+     showgrid="false"
+     inkscape:window-width="1440"
+     inkscape:window-height="840"
+     inkscape:window-x="-5"
+     inkscape:window-y="-3" />
+  <metadata
+     id="metadata7">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <g
+     inkscape:label="Layer 1"
+     inkscape:groupmode="layer"
+     id="layer1">
+    <g
+       id="g3178" />
+    <path
+       sodipodi:type="arc"
+       style="opacity:1;fill:url(#radialGradient5191);fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:11.30000019;stroke-linecap:butt;stroke-linejoin:miter;marker-start:none;stroke-miterlimit:16.79999924;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;filter:url(#filter3351)"
+       id="path3185"
+       sodipodi:cx="535.71429"
+       sodipodi:cy="680.93359"
+       sodipodi:rx="234.28572"
+       sodipodi:ry="234.28572"
+       d="M 770.00002,680.93359 A 234.28572,234.28572 0 1 1 301.42857,680.93359 A 234.28572,234.28572 0 1 1 770.00002,680.93359 z"
+       transform="translate(-156.52222,-149.8617)" />
+  </g>
+</svg>
diff --git a/sflphone-client-kde/icons/mailbox.svg b/sflphone-client-kde/src/icons/mailbox.svg
similarity index 100%
rename from sflphone-client-kde/icons/mailbox.svg
rename to sflphone-client-kde/src/icons/mailbox.svg
diff --git a/sflphone-client-kde/icons/mic.svg b/sflphone-client-kde/src/icons/mic.svg
similarity index 100%
rename from sflphone-client-kde/icons/mic.svg
rename to sflphone-client-kde/src/icons/mic.svg
diff --git a/sflphone-client-kde/icons/mic_25.svg b/sflphone-client-kde/src/icons/mic_25.svg
similarity index 100%
rename from sflphone-client-kde/icons/mic_25.svg
rename to sflphone-client-kde/src/icons/mic_25.svg
diff --git a/sflphone-client-kde/icons/mic_50.svg b/sflphone-client-kde/src/icons/mic_50.svg
similarity index 100%
rename from sflphone-client-kde/icons/mic_50.svg
rename to sflphone-client-kde/src/icons/mic_50.svg
diff --git a/sflphone-client-kde/icons/mic_75.svg b/sflphone-client-kde/src/icons/mic_75.svg
similarity index 100%
rename from sflphone-client-kde/icons/mic_75.svg
rename to sflphone-client-kde/src/icons/mic_75.svg
diff --git a/sflphone-client-kde/icons/missed.svg b/sflphone-client-kde/src/icons/missed.svg
similarity index 100%
rename from sflphone-client-kde/icons/missed.svg
rename to sflphone-client-kde/src/icons/missed.svg
diff --git a/sflphone-client-kde/icons/office-address-book.png b/sflphone-client-kde/src/icons/office-address-book.png
similarity index 100%
rename from sflphone-client-kde/icons/office-address-book.png
rename to sflphone-client-kde/src/icons/office-address-book.png
diff --git a/sflphone-client-kde/icons/outgoing.svg b/sflphone-client-kde/src/icons/outgoing.svg
similarity index 100%
rename from sflphone-client-kde/icons/outgoing.svg
rename to sflphone-client-kde/src/icons/outgoing.svg
diff --git a/sflphone-client-kde/icons/rec_call.svg b/sflphone-client-kde/src/icons/rec_call.svg
similarity index 100%
rename from sflphone-client-kde/icons/rec_call.svg
rename to sflphone-client-kde/src/icons/rec_call.svg
diff --git a/sflphone-client-kde/icons/record.svg b/sflphone-client-kde/src/icons/record.svg
similarity index 100%
rename from sflphone-client-kde/icons/record.svg
rename to sflphone-client-kde/src/icons/record.svg
diff --git a/sflphone-client-kde/icons/refuse.svg b/sflphone-client-kde/src/icons/refuse.svg
similarity index 100%
rename from sflphone-client-kde/icons/refuse.svg
rename to sflphone-client-kde/src/icons/refuse.svg
diff --git a/sflphone-client-kde/icons/remove.png b/sflphone-client-kde/src/icons/remove.png
similarity index 100%
rename from sflphone-client-kde/icons/remove.png
rename to sflphone-client-kde/src/icons/remove.png
diff --git a/sflphone-client-kde/icons/ring.svg b/sflphone-client-kde/src/icons/ring.svg
similarity index 100%
rename from sflphone-client-kde/icons/ring.svg
rename to sflphone-client-kde/src/icons/ring.svg
diff --git a/sflphone-client-kde/icons/sflphone.png b/sflphone-client-kde/src/icons/sflphone.png
similarity index 100%
rename from sflphone-client-kde/icons/sflphone.png
rename to sflphone-client-kde/src/icons/sflphone.png
diff --git a/sflphone-client-kde/icons/sflphone.svg b/sflphone-client-kde/src/icons/sflphone.svg
similarity index 100%
rename from sflphone-client-kde/icons/sflphone.svg
rename to sflphone-client-kde/src/icons/sflphone.svg
diff --git a/sflphone-client-kde/icons/sflphone_notif.svg b/sflphone-client-kde/src/icons/sflphone_notif.svg
similarity index 100%
rename from sflphone-client-kde/icons/sflphone_notif.svg
rename to sflphone-client-kde/src/icons/sflphone_notif.svg
diff --git a/sflphone-client-kde/icons/speaker.svg b/sflphone-client-kde/src/icons/speaker.svg
similarity index 100%
rename from sflphone-client-kde/icons/speaker.svg
rename to sflphone-client-kde/src/icons/speaker.svg
diff --git a/sflphone-client-kde/icons/speaker_25.svg b/sflphone-client-kde/src/icons/speaker_25.svg
similarity index 100%
rename from sflphone-client-kde/icons/speaker_25.svg
rename to sflphone-client-kde/src/icons/speaker_25.svg
diff --git a/sflphone-client-kde/icons/speaker_50.svg b/sflphone-client-kde/src/icons/speaker_50.svg
similarity index 100%
rename from sflphone-client-kde/icons/speaker_50.svg
rename to sflphone-client-kde/src/icons/speaker_50.svg
diff --git a/sflphone-client-kde/icons/speaker_75.svg b/sflphone-client-kde/src/icons/speaker_75.svg
similarity index 100%
rename from sflphone-client-kde/icons/speaker_75.svg
rename to sflphone-client-kde/src/icons/speaker_75.svg
diff --git a/sflphone-client-kde/icons/stock_person.svg b/sflphone-client-kde/src/icons/stock_person.svg
similarity index 100%
rename from sflphone-client-kde/icons/stock_person.svg
rename to sflphone-client-kde/src/icons/stock_person.svg
diff --git a/sflphone-client-kde/icons/transfert.svg b/sflphone-client-kde/src/icons/transfert.svg
similarity index 100%
rename from sflphone-client-kde/icons/transfert.svg
rename to sflphone-client-kde/src/icons/transfert.svg
diff --git a/sflphone-client-kde/icons/unhold.svg b/sflphone-client-kde/src/icons/unhold.svg
similarity index 100%
rename from sflphone-client-kde/icons/unhold.svg
rename to sflphone-client-kde/src/icons/unhold.svg
diff --git a/sflphone-client-kde/icons/x-office-address-book.png b/sflphone-client-kde/src/icons/x-office-address-book.png
similarity index 100%
rename from sflphone-client-kde/icons/x-office-address-book.png
rename to sflphone-client-kde/src/icons/x-office-address-book.png
diff --git a/sflphone-client-kde/instance_interface_singleton.cpp b/sflphone-client-kde/src/instance_interface_singleton.cpp
similarity index 100%
rename from sflphone-client-kde/instance_interface_singleton.cpp
rename to sflphone-client-kde/src/instance_interface_singleton.cpp
diff --git a/sflphone-client-kde/instance_interface_singleton.h b/sflphone-client-kde/src/instance_interface_singleton.h
similarity index 100%
rename from sflphone-client-kde/instance_interface_singleton.h
rename to sflphone-client-kde/src/instance_interface_singleton.h
diff --git a/sflphone-client-kde/main.cpp b/sflphone-client-kde/src/main.cpp
similarity index 89%
rename from sflphone-client-kde/main.cpp
rename to sflphone-client-kde/src/main.cpp
index d80209283c721882eab5de52ba5fb266e1d5bfdc..e968c54774fbcc5a4f63c229c5466fe3b16afe09 100644
--- a/sflphone-client-kde/main.cpp
+++ b/sflphone-client-kde/src/main.cpp
@@ -16,32 +16,16 @@
 #include "instance_interface_singleton.h"
 #include "sflphone_const.h"
 
+
+
 static const char description[] = I18N_NOOP("A KDE 4 Client for SFLPhone");
 
 static const char version[] = "0.9.5";
 
 int main(int argc, char **argv)
 {
-
-	///home/jquentin/.kde/share/apps/kabc
-/*	FILE *fp;
-	int status;
-	char path[PATH_MAX];
-
-
-	fp = popen("ls *", "r");
-	if (fp == NULL)
-		qDebug() << "marche pas";
-	while (fgets(path, PATH_MAX, fp) != NULL)
-	printf("%s", path);
-
-	status = pclose(fp);
-*/
-
 	try
 	{
-
-		
 		KLocale::setMainCatalog("sflphone-client-kde");
 		qDebug() << KLocale::defaultLanguage();
 		qDebug() << KLocale::defaultCountry();
@@ -64,9 +48,6 @@ int main(int argc, char **argv)
 		//options.add("+[URL]", ki18n( "Document to open" ));
 		KCmdLineArgs::addCmdLineOptions(options);
 		
-		
-		
-		
 		KApplication app;
 		
 		qDebug() << KGlobal::locale()->language();
diff --git a/sflphone-client-kde/src/qrc/resources.qrc b/sflphone-client-kde/src/qrc/resources.qrc
new file mode 100644
index 0000000000000000000000000000000000000000..73424bd026acebd196e9286adf706eb2c68f6644
--- /dev/null
+++ b/sflphone-client-kde/src/qrc/resources.qrc
@@ -0,0 +1,92 @@
+<RCC>
+  <qresource prefix="images" >
+    <file>../icons/sflphone.svg</file>
+    <file>../icons/sflphone_notif.svg</file>
+    <file>../icons/application-exit.png</file>
+    <file>../icons/office-address-book.png</file>
+    <file>../icons/x-office-address-book.png</file>
+    <file>../icons/add.png</file>
+    <file>../icons/remove.png</file>
+    <file>../icons/del_off.png</file>
+    <file>../icons/del_on.png</file>
+    <file>../icons/accept.svg</file>
+    <file>../icons/busy.svg</file>
+    <file>../icons/call.svg</file>
+    <file>../icons/current.svg</file>
+    <file>../icons/dial.svg</file>
+    <file>../icons/fail.svg</file>
+    <file>../icons/hang_up.svg</file>
+    <file>../icons/history2.svg</file>
+    <file>../icons/history.svg</file>
+    <file>../icons/hold.svg</file>
+    <file>../icons/application-exit.png</file>
+    <file>../icons/icon_accept.svg</file>
+    <file>../icons/icon_call.svg</file>
+    <file>../icons/icon_dialpad_off.svg</file>
+    <file>../icons/icon_dialpad.svg</file>
+    <file>../icons/icon_hangup.svg</file>
+    <file>../icons/icon_hold.svg</file>
+    <file>../icons/icon_rec.svg</file>
+    <file>../icons/icon_unhold.svg</file>
+    <file>../icons/icon_volume_off.svg</file>
+    <file>../icons/icon_volume.svg</file>
+    <file>../icons/incoming.svg</file>
+    <file>../icons/mailbox.svg</file>
+    <file>../icons/mic_25.svg</file>
+    <file>../icons/mic_50.svg</file>
+    <file>../icons/mic_75.svg</file>
+    <file>../icons/mic.svg</file>
+    <file>../icons/missed.svg</file>
+    <file>../icons/outgoing.svg</file>
+    <file>../icons/rec_call.svg</file>
+    <file>../icons/refuse.svg</file>
+    <file>../icons/ring.svg</file>
+    <file>../icons/sflphone.png</file>
+    <file>../icons/speaker_25.svg</file>
+    <file>../icons/speaker_50.svg</file>
+    <file>../icons/speaker_75.svg</file>
+    <file>../icons/speaker.svg</file>
+    <file>../icons/stock_person.svg</file>
+    <file>../icons/transfert.svg</file>
+    <file>../icons/unhold.svg</file>
+    <file>../icons/accept.svg</file>
+    <file>../icons/busy.svg</file>
+    <file>../icons/call.svg</file>
+    <file>../icons/current.svg</file>
+    <file>../icons/dial.svg</file>
+    <file>../icons/fail.svg</file>
+    <file>../icons/hang_up.svg</file>
+    <file>../icons/history2.svg</file>
+    <file>../icons/history.svg</file>
+    <file>../icons/hold.svg</file>
+    <file>../icons/icon_accept.svg</file>
+    <file>../icons/icon_call.svg</file>
+    <file>../icons/icon_dialpad_off.svg</file>
+    <file>../icons/icon_dialpad.svg</file>
+    <file>../icons/icon_hangup.svg</file>
+    <file>../icons/icon_hold.svg</file>
+    <file>../icons/icon_rec.svg</file>
+    <file>../icons/icon_unhold.svg</file>
+    <file>../icons/icon_volume_off.svg</file>
+    <file>../icons/icon_volume.svg</file>
+    <file>../icons/incoming.svg</file>
+    <file>../icons/mailbox.svg</file>
+    <file>../icons/mic_25.svg</file>
+    <file>../icons/mic_50.svg</file>
+    <file>../icons/mic_75.svg</file>
+    <file>../icons/mic.svg</file>
+    <file>../icons/missed.svg</file>
+    <file>../icons/outgoing.svg</file>
+    <file>../icons/rec_call.svg</file>
+    <file>../icons/refuse.svg</file>
+    <file>../icons/ring.svg</file>
+    <file>../icons/sflphone.png</file>
+    <file>../icons/speaker_25.svg</file>
+    <file>../icons/speaker_50.svg</file>
+    <file>../icons/speaker_75.svg</file>
+    <file>../icons/speaker.svg</file>
+    <file>../icons/stock_person.svg</file>
+    <file>../icons/transfert.svg</file>
+    <file>../icons/unhold.svg</file>
+  </qresource>
+</RCC>
diff --git a/sflphone-client-kde/sflphone_const.h b/sflphone-client-kde/src/sflphone_const.h
similarity index 90%
rename from sflphone-client-kde/sflphone_const.h
rename to sflphone-client-kde/src/sflphone_const.h
index c8a6838adaa4723419ce160bddc8f77eea688ef9..3f17b89d1dede5dccce9b7a699a3fa1fd730cb71 100644
--- a/sflphone-client-kde/sflphone_const.h
+++ b/sflphone-client-kde/src/sflphone_const.h
@@ -27,15 +27,17 @@
  * @brief Contains the global variables for the client code
  */
  
-#define APP_NAME                          "KDE Client"
+#define APP_NAME                          "SFLPhone KDE Client"
 
 /** Locale */
-#define _(STRING)                         gettext( STRING )   
+// #define _(STRING)                         gettext( STRING )   
 
 /** Warnings unused variables **/
-#define UNUSED_VAR(var)                   (void*)var
+// #define UNUSED_VAR(var)                   (void*)var
+
+// #define UNUSED                            __attribute__((__unused__))
+
 
-#define UNUSED                            __attribute__((__unused__))
 
 #define SIP                               0
 #define IAX                               1
@@ -105,6 +107,7 @@
 #define SOUND_DEVICE                      "speaker"
 
 
+/** Account details */
 #define ACCOUNT_TYPE                      "Account.type"
 #define ACCOUNT_ALIAS		               "Account.alias"
 #define ACCOUNT_ENABLED		               "Account.enable"
@@ -123,8 +126,10 @@
 #define ACCOUNT_TYPE_IAX                  "IAX"
 #define ACCOUNT_TYPES_TAB                 {QString(ACCOUNT_TYPE_SIP), QString(ACCOUNT_TYPE_IAX)}
 
+/** Constant variables */
 #define ACCOUNT_MAILBOX_DEFAULT_VALUE     "888"
 
+/** Account States */
 #define ACCOUNT_STATE_REGISTERED          "REGISTERED"
 #define ACCOUNT_STATE_UNREGISTERED        "UNREGISTERED"
 #define ACCOUNT_STATE_TRYING              "TRYING"
@@ -135,11 +140,12 @@
 #define ACCOUNT_STATE_ERROR_CONF_STUN     "ERROR_CONF_STUN"
 #define ACCOUNT_STATE_ERROR_EXIST_STUN    "ERROR_EXIST_STUN"
 
-
+/** Calls details */
 #define CALL_PEER_NAME                    "PEER_NAME"
 #define CALL_PEER_NUMBER                  "PEER_NUMBER"
 #define CALL_ACCOUNTID                    "ACCOUNTID"
 
+/** Call States */
 #define CALL_STATE_CHANGE_HUNG_UP         "HUNGUP"
 #define CALL_STATE_CHANGE_RINGING         "RINGING"
 #define CALL_STATE_CHANGE_CURRENT         "CURRENT"
@@ -149,12 +155,14 @@
 #define CALL_STATE_CHANGE_UNHOLD_CURRENT  "UNHOLD_CURRENT"
 #define CALL_STATE_CHANGE_UNHOLD_RECORD   "UNHOLD_RECORD"
 
+/** Address Book Settings */
 #define ADDRESSBOOK_MAX_RESULTS           "ADDRESSBOOK_MAX_RESULTS"
 #define ADDRESSBOOK_DISPLAY_CONTACT_PHOTO "ADDRESSBOOK_DISPLAY_CONTACT_PHOTO"
 #define ADDRESSBOOK_DISPLAY_BUSINESS      "ADDRESSBOOK_DISPLAY_PHONE_BUSINESS"
 #define ADDRESSBOOK_DISPLAY_HOME          "ADDRESSBOOK_DISPLAY_PHONE_HOME"
 #define ADDRESSBOOK_DISPLAY_MOBILE        "ADDRESSBOOK_DISPLAY_PHONE_MOBILE"
 
+/** Hooks settings */
 #define HOOKS_ADD_PREFIX                  "PHONE_NUMBER_HOOK_ADD_PREFIX"
 #define HOOKS_ENABLED                     "PHONE_NUMBER_HOOK_ENABLED"
 #define HOOKS_COMMAND                     "URLHOOK_COMMAND"
@@ -162,16 +170,21 @@
 #define HOOKS_SIP_ENABLED                 "URLHOOK_SIP_ENABLED"
 #define HOOKS_SIP_FIELD                   "URLHOOK_SIP_FIELD"
 
-
-
+/** Constant variables */
 #define MAX_HISTORY_CAPACITY              60
 
-
+/** Codecs details */
 #define CODEC_NAME                        0
 #define CODEC_SAMPLE_RATE                 1
 #define CODEC_BIT_RATE                    2
 #define CODEC_BANDWIDTH                   3
 
+/** Audio Managers */
+#define ALSA	                           0
+#define PULSEAUDIO                        1
+
+
+
 /** Error while opening capture device */
 #define ALSA_CAPTURE_DEVICE	            0x0001
 /** Error while opening playback device */
@@ -179,28 +192,11 @@
 /** Error pulseaudio */
 #define PULSEAUDIO_NOT_RUNNING            0x0100
 
-
-
 /** Tone to play when no voice mails */
 #define TONE_WITHOUT_MESSAGE              0
 /** Tone to play when voice mails */
 #define TONE_WITH_MESSAGE                 1
-/** Tells if the main window is reduced to the system tray or not */
-#define MINIMIZED	                        TRUE
-/** Behaviour of the main window on incoming calls */
-#define __POPUP_WINDOW                    ( dbus_popup_mode() )
-/** Show/Hide the dialpad */
-#define SHOW_DIALPAD	                     ( dbus_get_dialpad() ) 
-/** Show/Hide the volume controls */
-#define SHOW_VOLUME	                     ( dbus_get_volume_controls() ) 
-/** Show/Hide the dialpad */
-#define SHOW_SEARCHBAR	                  ( dbus_get_searchbar() ) 
-/** Show/Hide the alsa configuration panel */
-#define SHOW_ALSA_CONF                    ( dbus_get_audio_manager() == ALSA )
 
-/** Audio Managers */
-#define ALSA	                           0
-#define PULSEAUDIO                        1
 
 /** Notification levels */
 #define __NOTIF_LEVEL_MIN                 0
diff --git a/sflphone-client-kde/sflphone_kdeview.cpp b/sflphone-client-kde/src/sflphone_kdeview.cpp
similarity index 98%
rename from sflphone-client-kde/sflphone_kdeview.cpp
rename to sflphone-client-kde/src/sflphone_kdeview.cpp
index 5189686db0203e4692a7f99a47632f6e6eeb5b15..46ce96c459a4550d0ef1123d170dabe8001e105d 100644
--- a/sflphone-client-kde/sflphone_kdeview.cpp
+++ b/sflphone-client-kde/src/sflphone_kdeview.cpp
@@ -1,10 +1,11 @@
 /***************************************************************************
- *   Copyright (C) 2009 by Jérémy Quentin   *
- *   jeremy.quentin@gmail.com   *
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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     *
+ *   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,       *
@@ -32,6 +33,10 @@
 #include <kactioncollection.h>
 #include <kaction.h>
 
+#include <kabc/addressbook.h>
+#include <kabc/stdaddressbook.h>
+#include <kabc/addresseelist.h>
+
 #include "sflphone_const.h"
 #include "configurationmanager_interface_singleton.h"
 #include "callmanager_interface_singleton.h"
@@ -39,10 +44,8 @@
 #include "ActionSetAccountFirst.h"
 #include "ContactItemWidget.h"
 #include "SFLPhone.h"
+#include "typedefs.h"
 
-#include <kabc/addressbook.h>
-#include <kabc/stdaddressbook.h>
-#include <kabc/addresseelist.h>
 
 using namespace KABC;
 
@@ -78,6 +81,8 @@ sflphone_kdeView::sflphone_kdeView(QWidget *parent)
 	pal.setColor(QPalette::AlternateBase, Qt::lightGray);
 	setPalette(pal);
 	
+	stackedWidget_screen->setCurrentWidget(page_callList);
+	
 	loadWindow();
 	
 	
@@ -109,7 +114,6 @@ void sflphone_kdeView::loadWindow()
 	updateDialpad();
 	updateSearchHistory();
 	updateSearchAddressBook();
-	stackedWidget_screen->setCurrentWidget(page_callList);
 }
 
 QString sflphone_kdeView::firstAccountId()
@@ -447,6 +451,7 @@ void sflphone_kdeView::updateWindowCallState()
 					enabledActions[3] = false;
 					break;
 				case CALL_STATE_CURRENT:
+					qDebug() << "details = " << CallManagerInterfaceSingleton::getInstance().getCallDetails(call->getCallId()).value();
 					qDebug() << "Reached CALL_STATE_CURRENT with call " << (*callList)[item]->getCallId() << ". Updating window.";
 					recordEnabled = true;
 					break;
@@ -689,6 +694,11 @@ QVector<Contact *> sflphone_kdeView::findContactsInKAddressBook(QString textSear
 	return results;
 }
 
+/**
+ * 
+ * @return the integer resulting to the flags of the types chosen to be displayed in SFLPhone configuration.
+ * useful to sort contacts according to their types.
+ */
 int sflphone_kdeView::phoneNumberTypesDisplayed()
 {
 	ConfigurationManagerInterface & configurationManager = ConfigurationManagerInterfaceSingleton::getInstance();
@@ -1331,7 +1341,7 @@ void sflphone_kdeView::on1_error(MapStringString details)
 
 void sflphone_kdeView::on1_incomingCall(const QString &accountID, const QString & callID)
 {
-	qDebug() << "Signal : Incoming Call !";
+	qDebug() << "Signal : Incoming Call ! ID = " << callID;
 	ConfigurationManagerInterface & configurationManager = ConfigurationManagerInterfaceSingleton::getInstance();
 	Call * call = callList->addIncomingCall(callID);
 	addCallToCallList(call);
diff --git a/sflphone-client-kde/sflphone_kdeview.h b/sflphone-client-kde/src/sflphone_kdeview.h
similarity index 93%
rename from sflphone-client-kde/sflphone_kdeview.h
rename to sflphone-client-kde/src/sflphone_kdeview.h
index 2a64fc1763ea58b50e0e6dc18d2c8669e742eddb..20017b53fe277761ad7f46d94d4f9fbb3e0a2e16 100644
--- a/sflphone-client-kde/sflphone_kdeview.h
+++ b/sflphone-client-kde/src/sflphone_kdeview.h
@@ -1,10 +1,11 @@
 /***************************************************************************
- *   Copyright (C) 2009 by Jérémy Quentin   *
- *   jeremy.quentin@gmail.com   *
+ *   Copyright (C) 2009 by Savoir-Faire Linux                              *
+ *   Author : Jérémy Quentin                                               *
+ *   jeremy.quentin@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     *
+ *   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,       *
@@ -39,7 +40,6 @@
 
 #include "ui_sflphone_kdeview_base.h"
 
-class QPainter;
 class ConfigurationDialog;
 /**
  * This is the main view class for sflphone-client-kde.  Most of the non-menu,
@@ -64,21 +64,36 @@ private:
 	QErrorMessage * errorWindow;
 
 protected:
+	
+	/**
+	 * override context menu handling
+	 * @param event
+	 */
 	void contextMenuEvent(QContextMenuEvent *event);
 
 public:
+
+	//Constructors & Destructors
 	sflphone_kdeView(QWidget *parent);
 	virtual ~sflphone_kdeView();
-	
+	/**
+	 * 
+	 */
 	void loadWindow();
+	
+	//Getters
 	static QString firstAccountId();
 	static Account * firstRegisteredAccount();
 	static QVector<Account *> registeredAccounts();
 	static AccountList * getAccountList();
-	QVector<Contact *> findContactsInKAddressBook(QString textSearched, bool & full);
-	int phoneNumberTypesDisplayed();
 	QErrorMessage * getErrorWindow();
-
+	
+	//Daemon getters
+	int phoneNumberTypesDisplayed();
+	
+	//Updates
+	QVector<Contact *> findContactsInKAddressBook(QString textSearched, bool & full);
+	
 private slots:
 	void actionb(Call * call, call_action action);
 	void action(QListWidgetItem * item, call_action action);
diff --git a/sflphone-client-kde/src/typedefs.h b/sflphone-client-kde/src/typedefs.h
new file mode 100644
index 0000000000000000000000000000000000000000..cbd8cb3322c241ae0a4516867d1ca1144a7b73a7
--- /dev/null
+++ b/sflphone-client-kde/src/typedefs.h
@@ -0,0 +1,12 @@
+#ifndef TYPEDEFS_H
+#define TYPEDEFS_H
+
+#include <QtCore/QMetaType>
+#include <QtCore/QMap>
+#include <QtCore/QString>
+
+typedef QMap<QString, QString> MapStringString;
+typedef QMap<QString, int> MapStringInt;
+
+
+#endif
\ No newline at end of file
diff --git a/sflphone-client-kde/ConfigDialog.ui b/sflphone-client-kde/src/ui/ConfigDialog.ui
similarity index 100%
rename from sflphone-client-kde/ConfigDialog.ui
rename to sflphone-client-kde/src/ui/ConfigDialog.ui
diff --git a/sflphone-client-kde/sflphone_kdeview_base.ui b/sflphone-client-kde/src/ui/sflphone_kdeview_base.ui
similarity index 100%
rename from sflphone-client-kde/sflphone_kdeview_base.ui
rename to sflphone-client-kde/src/ui/sflphone_kdeview_base.ui
diff --git a/sflphone-common/globals.mak b/sflphone-common/globals.mak
index 820ab1f9e93395d43e469e9db4a44a35757ddbb3..37607028c3de133e8583ce0be41701d44309058f 100644
--- a/sflphone-common/globals.mak
+++ b/sflphone-common/globals.mak
@@ -1,7 +1,7 @@
 # Global variables
 src=$(top_srcdir)
-sflcodecdir=$(libdir)/sflphone/codecs
-sflplugindir=$(libdir)/sflphone/plugins
+sflcodecdir=$(DESTDIR)$(libdir)/sflphone/codecs
+sflplugindir=$(DESTDIR)$(libdir)/sflphone/plugins
 
 # for pjsip
 PJSIP_LIBS= \
diff --git a/sflphone-common/libs/stund/COPYING b/sflphone-common/libs/stund/COPYING
new file mode 100644
index 0000000000000000000000000000000000000000..bce8e8623fb6040913df4b5597679e5f86337cf3
--- /dev/null
+++ b/sflphone-common/libs/stund/COPYING
@@ -0,0 +1,50 @@
+/* ====================================================================
+ * The Vovida Software License, Version 1.0 
+ *
+ * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ * 
+ * 3. The names "VOCAL", "Vovida Open Communication Application Library",
+ *    and "Vovida Open Communication Application Library (VOCAL)" must
+ *    not be used to endorse or promote products derived from this
+ *    software without prior written permission. For written
+ *    permission, please contact vocal@vovida.org.
+ *
+ * 4. Products derived from this software may not be called "VOCAL", nor
+ *    may "VOCAL" appear in their name, without prior written
+ *    permission of Vovida Networks, Inc.
+ * 
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
+ * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
+ * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
+ * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by Vovida
+ * Networks, Inc. and many individuals on behalf of Vovida Networks,
+ * Inc.  For more information on Vovida Networks, Inc., please see
+ * <http://www.vovida.org/>.
+ *
+ */
+
+
diff --git a/sflphone-common/libs/stund/stun.cxx b/sflphone-common/libs/stund/stun.cxx
index 3343d6214bb403a0ed91751f8d1928a026d6baf8..33cb2e79cc6153bed7772f7495bdb10c52c3dd6c 100644
--- a/sflphone-common/libs/stund/stun.cxx
+++ b/sflphone-common/libs/stund/stun.cxx
@@ -1,3 +1,53 @@
+/* ====================================================================
+ * The Vovida Software License, Version 1.0 
+ *
+ * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ * 
+ * 3. The names "VOCAL", "Vovida Open Communication Application Library",
+ *    and "Vovida Open Communication Application Library (VOCAL)" must
+ *    not be used to endorse or promote products derived from this
+ *    software without prior written permission. For written
+ *    permission, please contact vocal@vovida.org.
+ *
+ * 4. Products derived from this software may not be called "VOCAL", nor
+ *    may "VOCAL" appear in their name, without prior written
+ *    permission of Vovida Networks, Inc.
+ * 
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
+ * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
+ * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
+ * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by Vovida
+ * Networks, Inc. and many individuals on behalf of Vovida Networks,
+ * Inc.  For more information on Vovida Networks, Inc., please see
+ * <http://www.vovida.org/>.
+ *
+ */
+
+
 #include <cassert>
 #include <cstring>
 #include <iostream>
@@ -2387,57 +2437,6 @@ stunOpenSocketPair( StunAddress4& dest, StunAddress4* mapAddr,
 	
    return false;
 }
-
-/* ====================================================================
- * The Vovida Software License, Version 1.0 
- * 
- * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- * 
- * 3. The names "VOCAL", "Vovida Open Communication Application Library",
- *    and "Vovida Open Communication Application Library (VOCAL)" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact vocal@vovida.org.
- *
- * 4. Products derived from this software may not be called "VOCAL", nor
- *    may "VOCAL" appear in their name, without prior written
- *    permission of Vovida Networks, Inc.
- * 
- * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
- * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
- * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
- * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- * DAMAGE.
- * 
- * ====================================================================
- * 
- * This software consists of voluntary contributions made by Vovida
- * Networks, Inc. and many individuals on behalf of Vovida Networks,
- * Inc.  For more information on Vovida Networks, Inc., please see
- * <http://www.vovida.org/>.
- *
- */
-
 // Local Variables:
 // mode:c++
 // c-file-style:"ellemtel"
diff --git a/sflphone-common/libs/stund/stun.h b/sflphone-common/libs/stund/stun.h
index cd4882f0c0f3549332d28f56de1cbe240c001cf5..c67b7014f57ff4f340e92dc70cd83bf62b1b1776 100644
--- a/sflphone-common/libs/stund/stun.h
+++ b/sflphone-common/libs/stund/stun.h
@@ -1,3 +1,54 @@
+/* ====================================================================
+ * The Vovida Software License, Version 1.0 
+ *
+ * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ * 
+ * 3. The names "VOCAL", "Vovida Open Communication Application Library",
+ *    and "Vovida Open Communication Application Library (VOCAL)" must
+ *    not be used to endorse or promote products derived from this
+ *    software without prior written permission. For written
+ *    permission, please contact vocal@vovida.org.
+ *
+ * 4. Products derived from this software may not be called "VOCAL", nor
+ *    may "VOCAL" appear in their name, without prior written
+ *    permission of Vovida Networks, Inc.
+ * 
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
+ * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
+ * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
+ * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by Vovida
+ * Networks, Inc. and many individuals on behalf of Vovida Networks,
+ * Inc.  For more information on Vovida Networks, Inc., please see
+ * <http://www.vovida.org/>.
+ *
+ */
+
+
+
 #ifndef STUN_H
 #define STUN_H
 
@@ -330,11 +381,6 @@ stunOpenSocketPair( StunAddress4& dest, StunAddress4* mappedAddr,
 #endif
 
 
-/* ====================================================================
- * The Vovida Software License, Version 1.0 
 * 
 * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 
 * 3. The names "VOCAL", "Vovida Open Communication Application Library",
 *    and "Vovida Open Communication Application Library (VOCAL)" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact vocal@vovida.org.
 *
 * 4. Products derived from this software may not be called "VOCAL", nor
 *    may "VOCAL" appear in their name, without prior written
 *    permission of Vovida Networks, Inc.
 * 
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
 * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
 * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
 * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 * 
 * ====================================================================
 * 
 * This software consists of voluntary contributions made by Vovida
 * Networks, Inc. and many individuals on behalf of Vovida Networks,
 * Inc.  For more information on Vovida Networks, Inc., please see
 * <http://www.vovida.org/>.
- *
- */
-
 // Local Variables:
 // mode:c++
 // c-file-style:"ellemtel"
diff --git a/sflphone-common/libs/stund/udp.cxx b/sflphone-common/libs/stund/udp.cxx
index fc58f26bf83d1b016f4d25bb2d976d8ea8b0dffd..23f3aaadc6d8b567189b855e74a69fa70d2661d3 100644
--- a/sflphone-common/libs/stund/udp.cxx
+++ b/sflphone-common/libs/stund/udp.cxx
@@ -1,3 +1,55 @@
+/* ====================================================================
+ * The Vovida Software License, Version 1.0 
+ * 
+ * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ * 
+ * 3. The names "VOCAL", "Vovida Open Communication Application Library",
+ *    and "Vovida Open Communication Application Library (VOCAL)" must
+ *    not be used to endorse or promote products derived from this
+ *    software without prior written permission. For written
+ *    permission, please contact vocal@vovida.org.
+ *
+ * 4. Products derived from this software may not be called "VOCAL", nor
+ *    may "VOCAL" appear in their name, without prior written
+ *    permission of Vovida Networks, Inc.
+ * 
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
+ * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
+ * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
+ * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * ====================================================================
+ * 
+ * This software consists of voluntary contributions made by Vovida
+ * Networks, Inc. and many individuals on behalf of Vovida Networks,
+ * Inc.  For more information on Vovida Networks, Inc., please see
+ * <http://www.vovida.org/>.
+ *
+ */
+
+
+
 #include <cassert>
 #include <cstdio>
 #include <cstring>
@@ -290,57 +342,6 @@ initNetwork()
 #endif
 }
 
-
-/* ====================================================================
- * The Vovida Software License, Version 1.0 
- * 
- * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- * 
- * 3. The names "VOCAL", "Vovida Open Communication Application Library",
- *    and "Vovida Open Communication Application Library (VOCAL)" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact vocal@vovida.org.
- *
- * 4. Products derived from this software may not be called "VOCAL", nor
- *    may "VOCAL" appear in their name, without prior written
- *    permission of Vovida Networks, Inc.
- * 
- * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
- * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
- * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
- * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- * DAMAGE.
- * 
- * ====================================================================
- * 
- * This software consists of voluntary contributions made by Vovida
- * Networks, Inc. and many individuals on behalf of Vovida Networks,
- * Inc.  For more information on Vovida Networks, Inc., please see
- * <http://www.vovida.org/>.
- *
- */
-
 // Local Variables:
 // mode:c++
 // c-file-style:"ellemtel"
diff --git a/sflphone-common/libs/stund/udp.h b/sflphone-common/libs/stund/udp.h
index 28af798d180c0ac2c7441d6ade2c03008c04dfc8..8eeb8fb88d4dcceee3ac7abddb4e8359e789ffdd 100644
--- a/sflphone-common/libs/stund/udp.h
+++ b/sflphone-common/libs/stund/udp.h
@@ -1,3 +1,55 @@
+/* ====================================================================
+ * The Vovida Software License, Version 1.0 
+ * 
+ * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ * 
+ * 3. The names "VOCAL", "Vovida Open Communication Application Library",
+ *    and "Vovida Open Communication Application Library (VOCAL)" must
+ *    not be used to endorse or promote products derived from this
+ *    software without prior written permission. For written
+ *    permission, please contact vocal@vovida.org.
+ *
+ * 4. Products derived from this software may not be called "VOCAL", nor
+ *    may "VOCAL" appear in their name, without prior written
+ *    permission of Vovida Networks, Inc.
+ * 
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
+ * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
+ * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
+ * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * ====================================================================
+ * 
+ * This software consists of voluntary contributions made by Vovida
+ * Networks, Inc. and many individuals on behalf of Vovida Networks,
+ * Inc.  For more information on Vovida Networks, Inc., please see
+ * <http://www.vovida.org/>.
+ *
+ */
+
+
+
 #ifndef udp_h
 #define udp_h
 
@@ -96,57 +148,6 @@ sendMessage( int fd, char* msg, int len,
 void
 initNetwork();
 
-
-/* ====================================================================
- * The Vovida Software License, Version 1.0 
- * 
- * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- * 
- * 3. The names "VOCAL", "Vovida Open Communication Application Library",
- *    and "Vovida Open Communication Application Library (VOCAL)" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact vocal@vovida.org.
- *
- * 4. Products derived from this software may not be called "VOCAL", nor
- *    may "VOCAL" appear in their name, without prior written
- *    permission of Vovida Networks, Inc.
- * 
- * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
- * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
- * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
- * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- * DAMAGE.
- * 
- * ====================================================================
- * 
- * This software consists of voluntary contributions made by Vovida
- * Networks, Inc. and many individuals on behalf of Vovida Networks,
- * Inc.  For more information on Vovida Networks, Inc., please see
- * <http://www.vovida.org/>.
- *
- */
-
 // Local Variables:
 // mode:c++
 // c-file-style:"ellemtel"
diff --git a/sflphone-common/src/account.cpp b/sflphone-common/src/account.cpp
index b50fc71fc49d5648d875ac8bc4cb99758b82a9d3..efadf2e6da0df636531d493217767e40ff349b10 100644
--- a/sflphone-common/src/account.cpp
+++ b/sflphone-common/src/account.cpp
@@ -48,8 +48,11 @@ void Account::loadConfig()
 }
 
 void Account::setRegistrationState( RegistrationState state ) { 
-    _registrationState = state; 
+    
+    if (state != _registrationState) {
+        _registrationState = state; 
 
-    // Notify the client
-    Manager::instance().connectionStatusNotification( );
+	// Notify the client
+	Manager::instance().connectionStatusNotification( );
+    }
 }
diff --git a/sflphone-common/src/audio/audiortp.cpp b/sflphone-common/src/audio/audiortp.cpp
index 72e640e93f3105c1352cc770e40146119268f5ba..9b07c1ff3be1996f1f770a6f224e4ce177163249 100644
--- a/sflphone-common/src/audio/audiortp.cpp
+++ b/sflphone-common/src/audio/audiortp.cpp
@@ -56,6 +56,8 @@ AudioRtp::createNewSession (SIPCall *ca) {
 
     ost::MutexLock m(_threadMutex);
 
+    _debug("AudioRtp::Create new rtp session\n");
+
     // something should stop the thread before...
     if ( _RTXThread != 0 ) { 
         _debug("**********************************************************\n");
@@ -86,7 +88,7 @@ AudioRtp::closeRtpSession () {
 
     ost::MutexLock m(_threadMutex);
     // This will make RTP threads finish.
-    _debug("Stopping AudioRTP\n");
+    _debug("AudioRtp::Stopping rtp session\n");
     try {
 
         delete _RTXThread; _RTXThread = 0;
diff --git a/sflphone-common/src/audio/audiortp.h b/sflphone-common/src/audio/audiortp.h
index 34d8b3ee1e7c982e029aeb7e35e81b367218c56f..65669dc5d8fc729e94d00af47d9f04d121cf4636 100644
--- a/sflphone-common/src/audio/audiortp.h
+++ b/sflphone-common/src/audio/audiortp.h
@@ -74,6 +74,9 @@ class AudioRtpRTX : public ost::Thread, public ost::TimerPort {
     /** A SIP call */
     SIPCall* _ca;    
 
+    
+    friend class RtpTest;
+
   private:
 
     // copy constructor
diff --git a/sflphone-common/src/managerimpl.cpp b/sflphone-common/src/managerimpl.cpp
index 1dce0670c722c6944db39deef445d3054a83e5af..1e9f84e97d7883804a334ae112abc39464f2e127 100644
--- a/sflphone-common/src/managerimpl.cpp
+++ b/sflphone-common/src/managerimpl.cpp
@@ -2176,6 +2176,7 @@ ManagerImpl::setConfig(const std::string& section, const std::string& name, int
 
 void ManagerImpl::setAccountsOrder (const std::string& order) 
 {
+    _debug("Set accounts order : %s\n", order.c_str() );
     // Set the new config
     setConfig (PREFERENCES, CONFIG_ACCOUNTS_ORDER, order);
 }
@@ -2532,13 +2533,18 @@ ManagerImpl::getAccountIdFromNameAndServer(const std::string& userName, const st
 {
   AccountMap::iterator iter;
   SIPAccount *account;
-
+  _debug("getAccountIdFromNameAndServer : username = %s , server = %s\n", userName.c_str(), server.c_str());
   // Try to find the account id from username and server name by full match
   for(iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) {
+    _debug("for : account = %s\n", iter->first.c_str());
     account = dynamic_cast<SIPAccount *>(iter->second);
+    _debug("account != NULL = %i\n", (account != NULL));
     if (account != NULL){
     	if(account->fullMatch(userName, server))
+    	{
+    			_debug("fullMatch\n");
       		return iter->first;
+      }
     }
   }
 
@@ -2547,7 +2553,22 @@ ManagerImpl::getAccountIdFromNameAndServer(const std::string& userName, const st
     account = dynamic_cast<SIPAccount *>(iter->second);
     if ( account != NULL ) {
     	if(account->hostnameMatch(server))
+    	{
+    	      _debug("hostnameMatch\n");
       		return iter->first;
+      }
+    }
+  }
+  
+  // We failed! Then only match the username
+  for(iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) {
+    account = dynamic_cast<SIPAccount *>(iter->second);
+    if ( account != NULL ) {
+    	if(account->userMatch(userName))
+    	{
+    	      _debug("userMatch\n");
+      		return iter->first;
+      }
     }
   }
 
@@ -2803,7 +2824,7 @@ std::map< std::string, std::string > ManagerImpl::getCallDetails(const CallID& c
 
     // So first we fetch the account
     accountid = getAccountFromCall (callID);
- _debug("%s\n",callID.c_str());
+    _debug("%s\n",callID.c_str());
     // Then the VoIP link this account is linked with (IAX2 or SIP)
     if ( (account=getAccount (accountid)) != 0) {
         link = account->getVoIPLink ();
diff --git a/sflphone-common/src/sipvoiplink.cpp b/sflphone-common/src/sipvoiplink.cpp
index 9cc3d9ca8b5bd9fb2c9a5030bc40504fd0551f5e..8a1f1976e0c761d8e0c1a921ff8e1d470fd48366 100644
--- a/sflphone-common/src/sipvoiplink.cpp
+++ b/sflphone-common/src/sipvoiplink.cpp
@@ -31,7 +31,7 @@
 
 #define CAN_REINVITE        1
 
-const pj_str_t STR_USER_AGENT = { (char*)"User-Agent", 10 };
+const pj_str_t STR_USER_AGENT = { ( char* ) "User-Agent", 10 };
 
 /**************** EXTERN VARIABLES AND FUNCTIONS (callbacks) **************************/
 
@@ -41,7 +41,7 @@ const pj_str_t STR_USER_AGENT = { (char*)"User-Agent", 10 };
  * @param rdata The request data
  * @param r_sdp The pjmedia_sdp_media to stock the remote SDP
  */
-void get_remote_sdp_from_offer( pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp );
+void get_remote_sdp_from_offer ( pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp );
 
 int getModId();
 
@@ -51,11 +51,11 @@ int getModId();
  * @param call a SIPCall valid pointer
  * @return bool True
  */
-bool setCallAudioLocal(SIPCall* call, std::string localIP, bool stun, std::string server);
+bool setCallAudioLocal ( SIPCall* call, std::string localIP, bool stun, std::string server );
 
-void handle_incoming_options (pjsip_rx_data *rxdata);
+void handle_incoming_options ( pjsip_rx_data *rxdata );
 
-std::string fetch_header_value (pjsip_msg *msg, std::string field);
+std::string fetch_header_value ( pjsip_msg *msg, std::string field );
 
 /*
  *  The global pool factory
@@ -65,7 +65,7 @@ pj_caching_pool _cp;
 /*
  * The pool to allocate memory
  */
-pj_pool_t *_pool;    
+pj_pool_t *_pool;
 
 /*
  *	The SIP endpoint
@@ -75,7 +75,7 @@ pjsip_endpoint *_endpt;
 /*
  *	The SIP module
  */
-pjsip_module _mod_ua;  
+pjsip_module _mod_ua;
 
 /*
  * Thread related
@@ -91,7 +91,7 @@ UrlHook *urlhook;
 /**
  * Get the number of voicemail waiting in a SIP message
  */
-void set_voicemail_info( AccountID account, pjsip_msg_body *body );
+void set_voicemail_info ( AccountID account, pjsip_msg_body *body );
 
 // Documentated from the PJSIP Developer's Guide, available on the pjsip website/
 
@@ -102,7 +102,7 @@ void set_voicemail_info( AccountID account, pjsip_msg_body *body );
  * @param	inv	A pointer on a pjsip_inv_session structure
  * @param	e	A pointer on a pjsip_event structure
  */
-void call_on_state_changed( pjsip_inv_session *inv, pjsip_event *e);
+void call_on_state_changed ( pjsip_inv_session *inv, pjsip_event *e );
 
 /*
  * Session callback
@@ -111,7 +111,7 @@ void call_on_state_changed( pjsip_inv_session *inv, pjsip_event *e);
  * @param	inv	A pointer on a pjsip_inv_session structure
  * @param	status	A pj_status_t structure
  */
-void call_on_media_update( pjsip_inv_session *inv UNUSED, pj_status_t status UNUSED);
+void call_on_media_update ( pjsip_inv_session *inv UNUSED, pj_status_t status UNUSED );
 
 /*
  * Called when the invite usage module has created a new dialog and invite
@@ -120,7 +120,7 @@ void call_on_media_update( pjsip_inv_session *inv UNUSED, pj_status_t status UNU
  * @param	inv	A pointer on a pjsip_inv_session structure
  * @param	e	A pointer on a pjsip_event structure
  */
-void call_on_forked(pjsip_inv_session *inv, pjsip_event *e);
+void call_on_forked ( pjsip_inv_session *inv, pjsip_event *e );
 
 /*
  * Session callback
@@ -131,2604 +131,2815 @@ void call_on_forked(pjsip_inv_session *inv, pjsip_event *e);
  * @param	tsx	A pointer on a pjsip_transaction structure
  * @param	e	A pointer on a pjsip_event structure
  */
-void call_on_tsx_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e);
+void call_on_tsx_changed ( pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e );
 
-void on_rx_offer( pjsip_inv_session *inv, const pjmedia_sdp_session *offer );
+void on_rx_offer ( pjsip_inv_session *inv, const pjmedia_sdp_session *offer );
 
 /*
  * Registration callback
  */
-void regc_cb(struct pjsip_regc_cbparam *param);
+void regc_cb ( struct pjsip_regc_cbparam *param );
 
 /*
  * Called to handle incoming requests outside dialogs
  * @param   rdata
  * @return  pj_bool_t
  */
-pj_bool_t mod_on_rx_request(pjsip_rx_data *rdata);
+pj_bool_t mod_on_rx_request ( pjsip_rx_data *rdata );
 
 /*
  * Called to handle incoming response
  * @param	rdata
  * @return	pj_bool_t
  */
-pj_bool_t mod_on_rx_response(pjsip_rx_data *rdata UNUSED) ;
+pj_bool_t mod_on_rx_response ( pjsip_rx_data *rdata UNUSED ) ;
 
 /*
  * Transfer callbacks
  */
-void xfer_func_cb( pjsip_evsub *sub, pjsip_event *event);
-void xfer_svr_cb(pjsip_evsub *sub, pjsip_event *event);
-void onCallTransfered(pjsip_inv_session *inv, pjsip_rx_data *rdata);
+void xfer_func_cb ( pjsip_evsub *sub, pjsip_event *event );
+void xfer_svr_cb ( pjsip_evsub *sub, pjsip_event *event );
+void onCallTransfered ( pjsip_inv_session *inv, pjsip_rx_data *rdata );
 
 /*************************************************************************************************/
 
 SIPVoIPLink* SIPVoIPLink::_instance = NULL;
 
 
-    SIPVoIPLink::SIPVoIPLink(const AccountID& accountID)
-    : VoIPLink(accountID)
-      , _nbTryListenAddr(2) // number of times to try to start SIP listener
-      , _stunServer("")
-    , _localExternAddress("") 
-    , _localExternPort(0)
-    , _audiortp(new AudioRtp())
-    ,_regPort(DEFAULT_SIP_PORT)
-    , _useStun(false)
-      , _clients(0)
+SIPVoIPLink::SIPVoIPLink ( const AccountID& accountID )
+		: VoIPLink ( accountID )
+		, _nbTryListenAddr ( 2 ) // number of times to try to start SIP listener
+		, _stunServer ( "" )
+		, _localExternAddress ( "" )
+		, _localExternPort ( 0 )
+		, _audiortp ( new AudioRtp() )
+		,_regPort ( DEFAULT_SIP_PORT )
+		, _useStun ( false )
+		, _clients ( 0 )
 {
-    // to get random number for RANDOM_PORT
-    srand (time(NULL));
+	// to get random number for RANDOM_PORT
+	srand ( time ( NULL ) );
 
-    urlhook = new UrlHook ();
+	urlhook = new UrlHook ();
 
-    /* Start pjsip initialization step */
-    init();
+	/* Start pjsip initialization step */
+	init();
 }
 
 SIPVoIPLink::~SIPVoIPLink()
 {
-    terminate();
+	terminate();
 }
 
-SIPVoIPLink* SIPVoIPLink::instance( const AccountID& id)
+SIPVoIPLink* SIPVoIPLink::instance ( const AccountID& id )
 {
 
-    if(!_instance ){
-        _instance = new SIPVoIPLink( id );
-    }
+	if ( !_instance )
+	{
+		_instance = new SIPVoIPLink ( id );
+	}
 
-    return _instance;
+	return _instance;
 }
 
-void SIPVoIPLink::decrementClients (void)
+void SIPVoIPLink::decrementClients ( void )
 {
-    _clients--;
-    if(_clients == 0){
-        terminate();
-        SIPVoIPLink::_instance=NULL;
-    }
+	_clients--;
+	if ( _clients == 0 )
+	{
+		terminate();
+		SIPVoIPLink::_instance=NULL;
+	}
 }
 
 bool SIPVoIPLink::init()
 {
-    if(initDone())
-        return false;
+	if ( initDone() )
+		return false;
 
-    /* Instanciate the C++ thread */
-    _evThread = new EventThread(this);
+	/* Instanciate the C++ thread */
+	_evThread = new EventThread ( this );
 
-    /* Initialize the pjsip library */
-    pjsip_init();
-    initDone(true);
+	/* Initialize the pjsip library */
+	pjsip_init();
+	initDone ( true );
 
-    return true;
+	return true;
 }
 
-    void 
+void
 SIPVoIPLink::terminate()
 {
-    if (_evThread){
-        delete _evThread; _evThread = NULL;
-    }
+	if ( _evThread )
+	{
+		delete _evThread; _evThread = NULL;
+	}
 
 
-    /* Clean shutdown of pjsip library */
-    if( initDone() )
-    {
-        pjsip_shutdown();
-    }
-    initDone(false);
+	/* Clean shutdown of pjsip library */
+	if ( initDone() )
+	{
+		pjsip_shutdown();
+	}
+	initDone ( false );
 }
 
-    void
+void
 SIPVoIPLink::terminateSIPCall()
 {
-    ost::MutexLock m(_callMapMutex);
-    CallMap::iterator iter = _callMap.begin();
-    SIPCall *call;
-    while( iter != _callMap.end() ) {
-        call = dynamic_cast<SIPCall*>(iter->second);
-        if (call) {
-            // terminate the sip call
-            delete call; call = 0;
-        }
-        iter++;
-    }
-    _callMap.clear();
+	ost::MutexLock m ( _callMapMutex );
+	CallMap::iterator iter = _callMap.begin();
+	SIPCall *call;
+	while ( iter != _callMap.end() )
+	{
+		call = dynamic_cast<SIPCall*> ( iter->second );
+		if ( call )
+		{
+			// terminate the sip call
+			delete call; call = 0;
+		}
+		iter++;
+	}
+	_callMap.clear();
 }
 
-    void
-SIPVoIPLink::terminateOneCall(const CallID& id)
+void
+SIPVoIPLink::terminateOneCall ( const CallID& id )
 {
 
-    SIPCall *call = getSIPCall(id);
-    if (call) {
-        // terminate the sip call
-        delete call; call = 0;
-    }
+	SIPCall *call = getSIPCall ( id );
+	if ( call )
+	{
+		// terminate the sip call
+		delete call; call = 0;
+	}
 }
 
-void get_remote_sdp_from_offer( pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp ){
+void get_remote_sdp_from_offer ( pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp )
+{
 
-    pjmedia_sdp_session *sdp;
-    pjsip_msg *msg;
-    pjsip_msg_body *body;
+	pjmedia_sdp_session *sdp;
+	pjsip_msg *msg;
+	pjsip_msg_body *body;
 
-    // Get the message
-    msg = rdata->msg_info.msg;
-    // Get the body message
-    body = msg->body;
+	// Get the message
+	msg = rdata->msg_info.msg;
+	// Get the body message
+	body = msg->body;
 
-    // Parse the remote request to get the sdp session
-    if (body) {   
-        pjmedia_sdp_parse( rdata->tp_info.pool, (char*)body->data, body->len, &sdp );
-        *r_sdp = sdp;
-    }
+	// Parse the remote request to get the sdp session
+	if ( body )
+	{
+		pjmedia_sdp_parse ( rdata->tp_info.pool, ( char* ) body->data, body->len, &sdp );
+		*r_sdp = sdp;
+	}
 
-    else
-        *r_sdp = NULL;
+	else
+		*r_sdp = NULL;
 }
 
 
-std::string SIPVoIPLink::get_useragent_name (void)
+std::string SIPVoIPLink::get_useragent_name ( void )
 {
-    std::ostringstream  useragent;
-    useragent << PROGNAME << "/" << SFLPHONED_VERSION;
-    return useragent.str();
+	std::ostringstream  useragent;
+	useragent << PROGNAME << "/" << SFLPHONED_VERSION;
+	return useragent.str();
 }
 
-    void
+void
 SIPVoIPLink::getEvent()
 {
-    // We have to register the external thread so it could access the pjsip framework
-    if(!pj_thread_is_registered())
-        pj_thread_register( NULL, desc, &thread );
-
-    // PJSIP polling
-    pj_time_val timeout = {0, 10};
-    pjsip_endpt_handle_events( _endpt, &timeout);
-
-}
-
-int SIPVoIPLink::sendRegister( AccountID id )
-{
-    pj_status_t status;
-    int expire_value;
-    char contactTmp[256];
-    pj_str_t svr, aor, contact, useragent;
-    pjsip_tx_data *tdata;
-    std::string tmp, hostname, username, password;
-    SIPAccount *account;
-    pjsip_regc *regc;
-    pjsip_generic_string_hdr *h;
-    pjsip_hdr hdr_list;
-
-    account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount(id));
-    hostname = account->getHostname();
-    username = account->getUsername();
-    password = account->getPassword();
-
-    _mutexSIP.enterMutex(); 
-
-    /* Get the client registration information for this particular account */
-    regc = account->getRegistrationInfo();
-    /* TODO If the registration already exists, delete it */
-    /*if(regc) {
-        status = pjsip_regc_destroy(regc);
-        regc = NULL;
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-    }*/
-
-    account->setRegister(true);
-
-    /* Set the expire value of the message from the config file */
-    expire_value = Manager::instance().getRegistrationExpireValue();
-
-    /* Update the state of the voip link */
-    account->setRegistrationState(Trying);
-
-    if (!validStunServer) {
-        account->setRegistrationState(ErrorExistStun);
-        account->setRegister(false);
-        _mutexSIP.leaveMutex(); 
-        return false;
-    }
-
-    /* Create the registration according to the account ID */
-    status = pjsip_regc_create(_endpt, (void*)account, &regc_cb, &regc);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to create regc.\n");
-        _mutexSIP.leaveMutex(); 
-        return false;
-    }
-
-    tmp = "sip:" + hostname;
-    pj_strdup2(_pool, &svr, tmp.data());
-
-    // tmp = "<sip:" + username + "@" + hostname + ";transport=tls>";
-    tmp = "<sip:" + username + "@" + hostname + ">";
-    pj_strdup2(_pool, &aor, tmp.data());
-
-    sprintf(contactTmp, "<sip:%s@%s:%d>", username.data(), _localExternAddress.data(), _localExternPort);
-    pj_strdup2(_pool, &contact, contactTmp);
-    account->setContact(contactTmp);
+	// We have to register the external thread so it could access the pjsip framework
+	if ( !pj_thread_is_registered() )
+		pj_thread_register ( NULL, desc, &thread );
+
+	// PJSIP polling
+	pj_time_val timeout = {0, 10};
+	pjsip_endpt_handle_events ( _endpt, &timeout );
+
+}
+
+int SIPVoIPLink::sendRegister ( AccountID id )
+{
+	pj_status_t status;
+	int expire_value;
+	char contactTmp[256];
+	pj_str_t svr, aor, contact, useragent;
+	pjsip_tx_data *tdata;
+	std::string tmp, hostname, username, password;
+	SIPAccount *account;
+	pjsip_regc *regc;
+	pjsip_generic_string_hdr *h;
+	pjsip_hdr hdr_list;
+
+	account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( id ) );
+	hostname = account->getHostname();
+	username = account->getUsername();
+	password = account->getPassword();
+
+	_mutexSIP.enterMutex();
+
+	/* Get the client registration information for this particular account */
+	regc = account->getRegistrationInfo();
+	/* TODO If the registration already exists, delete it */
+	/*if(regc) {
+	    status = pjsip_regc_destroy(regc);
+	    regc = NULL;
+	    PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
+	}*/
+
+	account->setRegister ( true );
+
+	/* Set the expire value of the message from the config file */
+	expire_value = Manager::instance().getRegistrationExpireValue();
+
+	/* Update the state of the voip link */
+	account->setRegistrationState ( Trying );
+
+	if ( !validStunServer )
+	{
+		account->setRegistrationState ( ErrorExistStun );
+		account->setRegister ( false );
+		_mutexSIP.leaveMutex();
+		return false;
+	}
+
+	/* Create the registration according to the account ID */
+	status = pjsip_regc_create ( _endpt, ( void* ) account, &regc_cb, &regc );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to create regc.\n" );
+		_mutexSIP.leaveMutex();
+		return false;
+	}
+
+	tmp = "sip:" + hostname;
+	pj_strdup2 ( _pool, &svr, tmp.data() );
+
+	// tmp = "<sip:" + username + "@" + hostname + ";transport=tls>";
+	tmp = "<sip:" + username + "@" + hostname + ">";
+	pj_strdup2 ( _pool, &aor, tmp.data() );
+
+	sprintf ( contactTmp, "<sip:%s@%s:%d>", username.data(), _localExternAddress.data(), _localExternPort );
+	pj_strdup2 ( _pool, &contact, contactTmp );
+	account->setContact ( contactTmp );
 
-    status = pjsip_regc_init(regc, &svr, &aor, &aor, 1, &contact, 600); //timeout);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to initialize regc. %d\n", status); //, regc->str_srv_url.ptr);
-        _mutexSIP.leaveMutex(); 
-        return false;
-    }
-
-    pjsip_cred_info *cred = account->getCredInfo();
-
-    if(!cred)
-        cred = new pjsip_cred_info();
-
-    pj_bzero(cred, sizeof (pjsip_cred_info));
-    pj_strdup2(_pool, &cred->username, username.data());
-    cred->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
-    pj_strdup2(_pool, &cred->data, password.data());
-    pj_strdup2(_pool, &cred->realm, "*");
-    pj_strdup2(_pool, &cred->scheme, "digest");
-    pjsip_regc_set_credentials(regc, 1, cred);
-
-    account->setCredInfo(cred);
-
-    // Add User-Agent Header
-    pj_list_init (&hdr_list);
-    useragent = pj_str( (char*)get_useragent_name ().c_str() );
-    h = pjsip_generic_string_hdr_create (_pool, &STR_USER_AGENT, &useragent);
-    pj_list_push_back (&hdr_list, (pjsip_hdr*)h);
-    pjsip_regc_add_headers (regc, &hdr_list);
-
-    status = pjsip_regc_register(regc, PJ_TRUE, &tdata);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to register regc.\n");
-        _mutexSIP.leaveMutex(); 
-        return false;
-    }
-
-    status = pjsip_regc_send(regc, tdata);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to send regc request.\n");
-        _mutexSIP.leaveMutex(); 
-        return false;
-    }
-
-    _mutexSIP.leaveMutex(); 
-
-    account->setRegistrationInfo(regc);
-
-    return true;
-}
-
-    int 
-SIPVoIPLink::sendUnregister (AccountID id)
-{
-    pj_status_t status = 0;
-    pjsip_tx_data *tdata = NULL;
-    SIPAccount *account;
-    pjsip_regc *regc;
-
-    account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount(id));
-    regc = account->getRegistrationInfo();
-
-    if(!account->isRegister()){
-        account->setRegistrationState(Unregistered); 
-        return true;
-    }
-
-    if(regc) {
-        status = pjsip_regc_unregister(regc, &tdata);
-        if(status != PJ_SUCCESS) {
-            _debug("UserAgent: Unable to unregister regc.\n");
-            return false;
-        }
-
-        status = pjsip_regc_send( regc, tdata );
-        if(status != PJ_SUCCESS) {
-            _debug("UserAgent: Unable to send regc request.\n");
-            return false;
-        }
-    } else {
-        _debug("UserAgent: regc is null!\n");
-        return false;
-    }
-
-    //account->setRegistrationInfo(regc);
-    account->setRegister(false);
-
-    return true;
-}
-
-    Call* 
-SIPVoIPLink::newOutgoingCall(const CallID& id, const std::string& toUrl)
-{
-    Account* account;
-    pj_status_t status;
-
-    SIPCall* call = new SIPCall(id, Call::Outgoing, _pool);
-
-
-    if (call) {
-        account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(Manager::instance().getAccountFromCall(id)));
-        if(!account)
-        {
-            _debug("Error retrieving the account to the make the call with\n");
-            call->setConnectionState(Call::Disconnected);
-            call->setState(Call::Error);
-            delete call; call=0;
-            return call;
-        }
-
-        call->setPeerNumber(getSipTo(toUrl, account->getHostname()));
-        setCallAudioLocal(call, getLocalIPAddress(), useStun(), getStunServer());
-
-        call->initRecFileName();
-
-        _debug("Try to make a call to: %s with call ID: %s\n", toUrl.data(), id.data());
-        // Building the local SDP offer
-        call->getLocalSDP()->set_ip_address(getLocalIP());
-        status = call->getLocalSDP()->create_initial_offer();
-    	if (status != PJ_SUCCESS) {
-            delete call; call=0;
-            return call;
-	}
-
-        if ( SIPOutgoingInvite(call) ) {
-            call->setConnectionState(Call::Progressing);
-            call->setState(Call::Active);
-            addCall(call);
-        } else {
-            delete call; call = 0;
-        }
-    }
-    return call;
-}
-
-    bool 
-SIPVoIPLink::answer(const CallID& id)
-{
-
-    int i;
-    SIPCall *call;
-    pj_status_t status;
-    pjsip_tx_data *tdata;
-    Sdp *local_sdp;
-    pjsip_inv_session *inv_session;
+	status = pjsip_regc_init ( regc, &svr, &aor, &aor, 1, &contact, 600 ); //timeout);
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to initialize regc. %d\n", status ); //, regc->str_srv_url.ptr);
+		_mutexSIP.leaveMutex();
+		return false;
+	}
+
+	pjsip_cred_info *cred = account->getCredInfo();
+
+	if ( !cred )
+		cred = new pjsip_cred_info();
+
+	pj_bzero ( cred, sizeof ( pjsip_cred_info ) );
+	pj_strdup2 ( _pool, &cred->username, username.data() );
+	cred->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
+	pj_strdup2 ( _pool, &cred->data, password.data() );
+	pj_strdup2 ( _pool, &cred->realm, "*" );
+	pj_strdup2 ( _pool, &cred->scheme, "digest" );
+	pjsip_regc_set_credentials ( regc, 1, cred );
+
+	account->setCredInfo ( cred );
+
+	// Add User-Agent Header
+	pj_list_init ( &hdr_list );
+	useragent = pj_str ( ( char* ) get_useragent_name ().c_str() );
+	h = pjsip_generic_string_hdr_create ( _pool, &STR_USER_AGENT, &useragent );
+	pj_list_push_back ( &hdr_list, ( pjsip_hdr* ) h );
+	pjsip_regc_add_headers ( regc, &hdr_list );
+
+	status = pjsip_regc_register ( regc, PJ_TRUE, &tdata );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to register regc.\n" );
+		_mutexSIP.leaveMutex();
+		return false;
+	}
 
-    _debug("SIPVoIPLink::answer: start answering \n");
+	status = pjsip_regc_send ( regc, tdata );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to send regc request.\n" );
+		_mutexSIP.leaveMutex();
+		return false;
+	}
 
-    call = getSIPCall(id);
+	_mutexSIP.leaveMutex();
 
-    if (call==0) {
-        _debug("! SIP Failure: SIPCall doesn't exists\n");
-        return false;
-    }
-
-    local_sdp = call->getLocalSDP();
-    inv_session = call->getInvSession();
-    status = local_sdp->start_negociation ();
-
-    if (status == PJ_SUCCESS) {
-        _debug("SIPVoIPLink::answer:UserAgent: Negociation success! : call %s \n", call->getCallId().c_str());
-        // Create and send a 200(OK) response
-        status = pjsip_inv_answer(inv_session, PJSIP_SC_OK, NULL, NULL, &tdata);
-        PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
-        status = pjsip_inv_send_msg(inv_session, tdata);
-        PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
-
-        // Start the RTP sessions
-        _debug("SIPVoIPLink::answer: Starting AudioRTP when answering : call %s \n", call->getCallId().c_str());
-        if (_audiortp->createNewSession(call) >= 0) {
-            call->setAudioStart(true);
-            call->setConnectionState(Call::Connected);
-            call->setState(Call::Active);
-            return true;
-        } else {
-            _debug("SIPVoIPLink::answer: Unable to start sound when answering %s/%d\n", __FILE__, __LINE__);
-        }
-    }
-    else {
-        // Create and send a 488/Not acceptable here
-        // because the SDP negociation failed
-        status = pjsip_inv_answer( inv_session, PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL,
-                &tdata );
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-        status = pjsip_inv_send_msg( inv_session, tdata );
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
+	account->setRegistrationInfo ( regc );
 
-        // Terminate the call
-        _debug("SIPVoIPLink::answer: fail terminate call %s \n",call->getCallId().c_str());
-        terminateOneCall(call->getCallId());
-        removeCall(call->getCallId());
-        return false;
-    }
+	return true;
 }
 
-    bool
-SIPVoIPLink::hangup(const CallID& id)
+int
+SIPVoIPLink::sendUnregister ( AccountID id )
 {
-    pj_status_t status;
-    pjsip_tx_data *tdata = NULL;
-    SIPCall* call;
+	pj_status_t status = 0;
+	pjsip_tx_data *tdata = NULL;
+	SIPAccount *account;
+	pjsip_regc *regc;
+
+	account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( id ) );
+	regc = account->getRegistrationInfo();
+
+	if ( !account->isRegister() )
+	{
+		account->setRegistrationState ( Unregistered );
+		return true;
+	}
 
-    call = getSIPCall(id);
+	if ( regc )
+	{
+		status = pjsip_regc_unregister ( regc, &tdata );
+		if ( status != PJ_SUCCESS )
+		{
+			_debug ( "UserAgent: Unable to unregister regc.\n" );
+			return false;
+		}
+
+		status = pjsip_regc_send ( regc, tdata );
+		if ( status != PJ_SUCCESS )
+		{
+			_debug ( "UserAgent: Unable to send regc request.\n" );
+			return false;
+		}
+	}
+	else
+	{
+		_debug ( "UserAgent: regc is null!\n" );
+		return false;
+	}
 
-    if (call==0) { _debug("! SIP Error: Call doesn't exist\n"); return false; }  
-    
-    // User hangup current call. Notify peer
-    status = pjsip_inv_end_session(call->getInvSession(), 404, NULL, &tdata);
-    if(status != PJ_SUCCESS)
-        return false;
-    
+	//account->setRegistrationInfo(regc);
+	account->setRegister ( false );
 
-    if(tdata == NULL)
-        return true;
-    // _debug("Some tdata info: %",);
+	return true;
+}
 
-    
-    status = pjsip_inv_send_msg(call->getInvSession(), tdata);
-    if(status != PJ_SUCCESS)
-        return false;
+Call*
+SIPVoIPLink::newOutgoingCall ( const CallID& id, const std::string& toUrl )
+{
+	Account* account;
+	pj_status_t status;
+
+	SIPCall* call = new SIPCall ( id, Call::Outgoing, _pool );
+
+
+	if ( call )
+	{
+		account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( Manager::instance().getAccountFromCall ( id ) ) );
+		if ( !account )
+		{
+			_debug ( "Error retrieving the account to the make the call with\n" );
+			call->setConnectionState ( Call::Disconnected );
+			call->setState ( Call::Error );
+			delete call; call=0;
+			return call;
+		}
+
+		call->setPeerNumber ( getSipTo ( toUrl, account->getHostname() ) );
+		setCallAudioLocal ( call, getLocalIPAddress(), useStun(), getStunServer() );
+
+		call->initRecFileName();
+
+		_debug ( "Try to make a call to: %s with call ID: %s\n", toUrl.data(), id.data() );
+		// Building the local SDP offer
+		call->getLocalSDP()->set_ip_address ( getLocalIP() );
+		status = call->getLocalSDP()->create_initial_offer();
+		if ( status != PJ_SUCCESS )
+		{
+			delete call; call=0;
+			return call;
+		}
+
+		if ( SIPOutgoingInvite ( call ) )
+		{
+			call->setConnectionState ( Call::Progressing );
+			call->setState ( Call::Active );
+			addCall ( call );
+		}
+		else
+		{
+			delete call; call = 0;
+		}
+	}
+	return call;
+}
 
+bool
+SIPVoIPLink::answer ( const CallID& id )
+{
 
-    call->getInvSession()->mod_data[getModId()] = NULL;
+	int i;
+	SIPCall *call;
+	pj_status_t status;
+	pjsip_tx_data *tdata;
+	Sdp *local_sdp;
+	pjsip_inv_session *inv_session;
 
+	_debug ( "SIPVoIPLink::answer: start answering \n" );
 
-    // Release RTP thread
-    if (Manager::instance().isCurrentCall(id)) {
-        _debug("* SIP Info: Stopping AudioRTP for hangup\n");
-        _audiortp->closeRtpSession();
-    }
+	call = getSIPCall ( id );
 
-    terminateOneCall(id);
-    removeCall(id);
+	if ( call==0 )
+	{
+		_debug ( "! SIP Failure: SIPCall doesn't exists\n" );
+		return false;
+	}
 
-    return true;
+	local_sdp = call->getLocalSDP();
+	inv_session = call->getInvSession();
+	status = local_sdp->start_negociation ();
+
+	if ( status == PJ_SUCCESS )
+	{
+		_debug ( "SIPVoIPLink::answer:UserAgent: Negociation success! : call %s \n", call->getCallId().c_str() );
+		// Create and send a 200(OK) response
+		status = pjsip_inv_answer ( inv_session, PJSIP_SC_OK, NULL, NULL, &tdata );
+		PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+		status = pjsip_inv_send_msg ( inv_session, tdata );
+		PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+		// Start the RTP sessions
+		_debug ( "SIPVoIPLink::answer: Starting AudioRTP when answering : call %s \n", call->getCallId().c_str() );
+		if ( _audiortp->createNewSession ( call ) >= 0 )
+		{
+			call->setAudioStart ( true );
+			call->setConnectionState ( Call::Connected );
+			call->setState ( Call::Active );
+			return true;
+		}
+		else
+		{
+			_debug ( "SIPVoIPLink::answer: Unable to start sound when answering %s/%d\n", __FILE__, __LINE__ );
+		}
+	}
+	else
+	{
+		// Create and send a 488/Not acceptable here
+		// because the SDP negociation failed
+		status = pjsip_inv_answer ( inv_session, PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL,
+		                            &tdata );
+		PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+		status = pjsip_inv_send_msg ( inv_session, tdata );
+		PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+		// Terminate the call
+		_debug ( "SIPVoIPLink::answer: fail terminate call %s \n",call->getCallId().c_str() );
+		terminateOneCall ( call->getCallId() );
+		removeCall ( call->getCallId() );
+		return false;
+	}
 }
 
-    bool
-SIPVoIPLink::peerHungup(const CallID& id)
+bool
+SIPVoIPLink::hangup ( const CallID& id )
 {
-    pj_status_t status;
-    pjsip_tx_data *tdata = NULL;
-    SIPCall* call;
+	pj_status_t status;
+	pjsip_tx_data *tdata = NULL;
+	SIPCall* call;
 
-    call = getSIPCall(id);
+	call = getSIPCall ( id );
 
-    if (call==0) { _debug("! SIP Error: Call doesn't exist\n"); return false; }  
+	if ( call==0 ) { _debug ( "! SIP Error: Call doesn't exist\n" ); return false; }
 
-    // User hangup current call. Notify peer
-    status = pjsip_inv_end_session(call->getInvSession(), 404, NULL, &tdata);
-    if(status != PJ_SUCCESS)
-        return false;
+	// User hangup current call. Notify peer
+	status = pjsip_inv_end_session ( call->getInvSession(), 404, NULL, &tdata );
+	if ( status != PJ_SUCCESS )
+		return false;
 
-    if(tdata == NULL)
-        return true;
 
-    status = pjsip_inv_send_msg(call->getInvSession(), tdata);
-    if(status != PJ_SUCCESS)
-        return false;
+	if ( tdata == NULL )
+		return true;
+	// _debug("Some tdata info: %",);
 
-    call->getInvSession()->mod_data[getModId()] = NULL;
 
-    // Release RTP thread
-    if (Manager::instance().isCurrentCall(id)) {
-        _debug("* SIP Info: Stopping AudioRTP for hangup\n");
-        _audiortp->closeRtpSession();
-    }
+	status = pjsip_inv_send_msg ( call->getInvSession(), tdata );
+	if ( status != PJ_SUCCESS )
+		return false;
 
-    terminateOneCall(id);
-    removeCall(id);
 
-    return true;
+	call->getInvSession()->mod_data[getModId() ] = NULL;
+
+
+	// Release RTP thread
+	if ( Manager::instance().isCurrentCall ( id ) )
+	{
+		_debug ( "* SIP Info: Stopping AudioRTP for hangup\n" );
+		_audiortp->closeRtpSession();
+	}
+
+	terminateOneCall ( id );
+	removeCall ( id );
+
+	return true;
 }
 
-    bool
-SIPVoIPLink::cancel(const CallID& id)
+bool
+SIPVoIPLink::peerHungup ( const CallID& id )
 {
-    SIPCall* call = getSIPCall(id);
-    if (call==0) { _debug("! SIP Error: Call doesn't exist\n"); return false; }  
+	pj_status_t status;
+	pjsip_tx_data *tdata = NULL;
+	SIPCall* call;
+
+	call = getSIPCall ( id );
+
+	if ( call==0 ) { _debug ( "! SIP Error: Call doesn't exist\n" ); return false; }
+
+	// User hangup current call. Notify peer
+	status = pjsip_inv_end_session ( call->getInvSession(), 404, NULL, &tdata );
+	if ( status != PJ_SUCCESS )
+		return false;
 
-    _debug("- SIP Action: Cancel call %s [cid: %3d]\n", id.data(), call->getCid()); 
+	if ( tdata == NULL )
+		return true;
 
-    terminateOneCall(id);
-    removeCall(id);
+	status = pjsip_inv_send_msg ( call->getInvSession(), tdata );
+	if ( status != PJ_SUCCESS )
+		return false;
+
+	call->getInvSession()->mod_data[getModId() ] = NULL;
+
+	// Release RTP thread
+	if ( Manager::instance().isCurrentCall ( id ) )
+	{
+		_debug ( "* SIP Info: Stopping AudioRTP for hangup\n" );
+		_audiortp->closeRtpSession();
+	}
 
-    return true;
+	terminateOneCall ( id );
+	removeCall ( id );
+
+	return true;
+}
+
+bool
+SIPVoIPLink::cancel ( const CallID& id )
+{
+	SIPCall* call = getSIPCall ( id );
+	if ( call==0 ) { _debug ( "! SIP Error: Call doesn't exist\n" ); return false; }
+
+	_debug ( "- SIP Action: Cancel call %s [cid: %3d]\n", id.data(), call->getCid() );
+
+	terminateOneCall ( id );
+	removeCall ( id );
+
+	return true;
 }
 
-    bool
-SIPVoIPLink::onhold(const CallID& id)
+bool
+SIPVoIPLink::onhold ( const CallID& id )
 {
 
-    pj_status_t status;
-    SIPCall* call;
+	pj_status_t status;
+	SIPCall* call;
 
-    call = getSIPCall(id);
+	call = getSIPCall ( id );
 
-    if (call==0) { _debug("! SIP Error: call doesn't exist\n"); return false; }  
+	if ( call==0 ) { _debug ( "! SIP Error: call doesn't exist\n" ); return false; }
 
 
-    // Stop sound
-    call->setAudioStart(false);
-    call->setState(Call::Hold);
-    _debug("* SIP Info: Stopping AudioRTP for onhold action\n");
-    _audiortp->closeRtpSession();
+	// Stop sound
+	call->setAudioStart ( false );
+	call->setState ( Call::Hold );
+	_debug ( "* SIP Info: Stopping AudioRTP for onhold action\n" );
+	_audiortp->closeRtpSession();
 
-    /* Create re-INVITE with new offer */
-    status = inv_session_reinvite (call, "sendonly");
-    if (status != PJ_SUCCESS)
-        return false;
+	/* Create re-INVITE with new offer */
+	status = inv_session_reinvite ( call, "sendonly" );
+	if ( status != PJ_SUCCESS )
+		return false;
 
-    return true;
+	return true;
 }
 
-int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction) {
+int SIPVoIPLink::inv_session_reinvite ( SIPCall *call, std::string direction )
+{
+
+	pj_status_t status;
+	pjsip_tx_data *tdata;
+	pjmedia_sdp_session *local_sdp;
+	pjmedia_sdp_attr *attr;
 
-    pj_status_t status;
-    pjsip_tx_data *tdata;
-    pjmedia_sdp_session *local_sdp;
-    pjmedia_sdp_attr *attr;
+	local_sdp = call->getLocalSDP()->get_local_sdp_session();
 
-    local_sdp = call->getLocalSDP()->get_local_sdp_session();
+	if ( local_sdp == NULL )
+	{
+		_debug ( "! SIP Failure: unable to find local_sdp\n" );
+		return !PJ_SUCCESS;
+	}
 
-    if( local_sdp == NULL ){
-        _debug("! SIP Failure: unable to find local_sdp\n");
-        return !PJ_SUCCESS;
-    }
+	// reinvite only if connected
+	// Build the local SDP offer
+	status = call->getLocalSDP()->create_initial_offer( );
+	if ( status != PJ_SUCCESS )
+		return 1;   // !PJ_SUCCESS
 
-    // reinvite only if connected
-    // Build the local SDP offer
-    status = call->getLocalSDP()->create_initial_offer( );
-    if (status != PJ_SUCCESS)
-        return 1;   // !PJ_SUCCESS 
+	pjmedia_sdp_media_remove_all_attr ( local_sdp->media[0], "sendrecv" );
+	attr = pjmedia_sdp_attr_create ( _pool, direction.c_str(), NULL );
+	pjmedia_sdp_media_add_attr ( local_sdp->media[0], attr );
 
-    pjmedia_sdp_media_remove_all_attr(local_sdp->media[0], "sendrecv");
-    attr = pjmedia_sdp_attr_create(_pool, direction.c_str(), NULL);
-    pjmedia_sdp_media_add_attr(local_sdp->media[0], attr);
+	// Build the reinvite request
+	status = pjsip_inv_reinvite ( call->getInvSession(), NULL,
+	                              local_sdp, &tdata );
+	if ( status != PJ_SUCCESS )
+		return 1;   // !PJ_SUCCESS
 
-    // Build the reinvite request
-    status = pjsip_inv_reinvite( call->getInvSession(), NULL,
-            local_sdp, &tdata );
-    if (status != PJ_SUCCESS)
-        return 1;   // !PJ_SUCCESS 
+	// Send it
+	status = pjsip_inv_send_msg ( call->getInvSession(), tdata );
+	if ( status != PJ_SUCCESS )
+		return 1;   // !PJ_SUCCESS
 
-    // Send it
-    status = pjsip_inv_send_msg( call->getInvSession(), tdata );
-    if (status != PJ_SUCCESS)
-        return 1;   // !PJ_SUCCESS 
-    
-    return PJ_SUCCESS;
+	return PJ_SUCCESS;
 }
 
 
-    bool 
-SIPVoIPLink::offhold(const CallID& id)
+bool
+SIPVoIPLink::offhold ( const CallID& id )
 {
-    SIPCall *call;
-    pj_status_t status;
-
-    call = getSIPCall(id);
+	SIPCall *call;
+	pj_status_t status;
 
-    if (call==0) { 
-        _debug("! SIP Error: Call doesn't exist\n"); 
-        return false; 
-    }
+	call = getSIPCall ( id );
 
-    /* Create re-INVITE with new offer */
-    status = inv_session_reinvite (call, "sendrecv");
-    if (status != PJ_SUCCESS)
-        return false;
+	if ( call==0 )
+	{
+		_debug ( "! SIP Error: Call doesn't exist\n" );
+		return false;
+	}
 
-    // Enable audio
-    _debug("* SIP Info: Starting AudioRTP when offhold\n");
-    call->setState(Call::Active);
-    // it's sure that this is the current call id...
-    if (_audiortp->createNewSession(call) < 0) {
-        _debug("! SIP Failure: Unable to start sound (%s:%d)\n", __FILE__, __LINE__);
-        return false;
-    }
+	/* Create re-INVITE with new offer */
+	status = inv_session_reinvite ( call, "sendrecv" );
+	if ( status != PJ_SUCCESS )
+		return false;
+
+	// Enable audio
+	_debug ( "* SIP Info: Starting AudioRTP when offhold\n" );
+	call->setState ( Call::Active );
+	// it's sure that this is the current call id...
+	if ( _audiortp->createNewSession ( call ) < 0 )
+	{
+		_debug ( "! SIP Failure: Unable to start sound (%s:%d)\n", __FILE__, __LINE__ );
+		return false;
+	}
 
-    return true;
+	return true;
 }
 
-    bool 
-SIPVoIPLink::transfer(const CallID& id, const std::string& to)
+bool
+SIPVoIPLink::transfer ( const CallID& id, const std::string& to )
 {
 
-    SIPCall *call;
-    std::string tmp_to;
-    pjsip_evsub *sub;
-    pjsip_tx_data *tdata;
-    struct pjsip_evsub_user xfer_cb;
-    pj_status_t status;
-    pj_str_t dest;
-    AccountID account_id;
-    Account* account;
+	SIPCall *call;
+	std::string tmp_to;
+	pjsip_evsub *sub;
+	pjsip_tx_data *tdata;
+	struct pjsip_evsub_user xfer_cb;
+	pj_status_t status;
+	pj_str_t dest;
+	AccountID account_id;
+	Account* account;
+
+	call = getSIPCall ( id );
+	call->stopRecording();
+	account_id = Manager::instance().getAccountFromCall ( id );
+	account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( account_id ) );
+
+	if ( call==0 )
+	{
+		_debug ( "! SIP Failure: Call doesn't exist\n" );
+		return false;
+	}
+
+	tmp_to = SIPToHeader ( to );
+	if ( account )
+	{
+		if ( tmp_to.find ( "@" ) == std::string::npos )
+		{
+			tmp_to = tmp_to + "@" + account->getHostname();
+		}
+	}
+
+	else
+	{
+
+	}
+
+	_debug ( "In transfer, tmp_to is %s\n", tmp_to.data() );
 
-    call = getSIPCall(id);
-    call->stopRecording();
-    account_id = Manager::instance().getAccountFromCall(id);
-    account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(account_id));
-
-    if (call==0) { 
-        _debug("! SIP Failure: Call doesn't exist\n"); 
-        return false; 
-    }  
-
-    tmp_to = SIPToHeader(to);
-    if (account) {
-        if (tmp_to.find("@") == std::string::npos) {
-            tmp_to = tmp_to + "@" + account->getHostname();
-        }
-    }
-
-    else {
-        
-    }
-
-    _debug("In transfer, tmp_to is %s\n", tmp_to.data());
-
-    pj_strdup2(_pool, &dest, tmp_to.data());
-
-    /* Create xfer client subscription. */
-    pj_bzero(&xfer_cb, sizeof(xfer_cb));
-    xfer_cb.on_evsub_state = &xfer_func_cb;
-
-    status = pjsip_xfer_create_uac(call->getInvSession()->dlg, &xfer_cb, &sub);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to create xfer -- %d\n", status);
-        return false;
-    }
-
-    /* Associate this voiplink of call with the client subscription 
-     * We can not just associate call with the client subscription
-     * because after this function, we can not find the cooresponding
-     * voiplink from the call any more. But the voiplink is useful!
-     */
-    pjsip_evsub_set_mod_data(sub, getModId(), this);
- 
-    _debug ("SIP port listener = %i ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", _localExternPort);
-
-    /*
-     * Create REFER request.
-     */
-    status = pjsip_xfer_initiate(sub, &dest, &tdata);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to create REFER request -- %d\n", status);
-        return false;
-    }
+	pj_strdup2 ( _pool, &dest, tmp_to.data() );
 
-    /* Send. */
-    status = pjsip_xfer_send_request(sub, tdata);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to send REFER request -- %d\n", status);
-        return false;
-    }
-
-    return true;
+	/* Create xfer client subscription. */
+	pj_bzero ( &xfer_cb, sizeof ( xfer_cb ) );
+	xfer_cb.on_evsub_state = &xfer_func_cb;
+
+	status = pjsip_xfer_create_uac ( call->getInvSession()->dlg, &xfer_cb, &sub );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to create xfer -- %d\n", status );
+		return false;
+	}
+
+	/* Associate this voiplink of call with the client subscription
+	 * We can not just associate call with the client subscription
+	 * because after this function, we can not find the cooresponding
+	 * voiplink from the call any more. But the voiplink is useful!
+	 */
+	pjsip_evsub_set_mod_data ( sub, getModId(), this );
+
+	_debug ( "SIP port listener = %i ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", _localExternPort );
+
+	/*
+	 * Create REFER request.
+	 */
+	status = pjsip_xfer_initiate ( sub, &dest, &tdata );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to create REFER request -- %d\n", status );
+		return false;
+	}
+
+	/* Send. */
+	status = pjsip_xfer_send_request ( sub, tdata );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to send REFER request -- %d\n", status );
+		return false;
+	}
+
+	return true;
 }
 
 bool SIPVoIPLink::transferStep2()
 {
-    _audiortp->closeRtpSession();
-    return true;
+	_audiortp->closeRtpSession();
+	return true;
 }
 
-    bool
-SIPVoIPLink::refuse (const CallID& id)
+bool
+SIPVoIPLink::refuse ( const CallID& id )
 {
-    SIPCall *call;
-    pj_status_t status;
-    pjsip_tx_data *tdata;
+	SIPCall *call;
+	pj_status_t status;
+	pjsip_tx_data *tdata;
+
 
-    
-    call = getSIPCall(id);
+	call = getSIPCall ( id );
 
-    if (call==0) { 
-        _debug("Call doesn't exist\n"); 
-        return false; 
-    }  
+	if ( call==0 )
+	{
+		_debug ( "Call doesn't exist\n" );
+		return false;
+	}
 
-    // can't refuse outgoing call or connected
-    if (!call->isIncoming() || call->getConnectionState() == Call::Connected) { 
-        _debug("It's not an incoming call, or it's already answered\n");
-        return false; 
-    }
+	// can't refuse outgoing call or connected
+	if ( !call->isIncoming() || call->getConnectionState() == Call::Connected )
+	{
+		_debug ( "It's not an incoming call, or it's already answered\n" );
+		return false;
+	}
 
-    // User refuse current call. Notify peer
-    status = pjsip_inv_end_session(call->getInvSession(), PJSIP_SC_DECLINE, NULL, &tdata); //603
-    if(status != PJ_SUCCESS)
-        return false;
+	// User refuse current call. Notify peer
+	status = pjsip_inv_end_session ( call->getInvSession(), PJSIP_SC_DECLINE, NULL, &tdata ); //603
+	if ( status != PJ_SUCCESS )
+		return false;
 
-    status = pjsip_inv_send_msg(call->getInvSession(), tdata);
-    if(status != PJ_SUCCESS)
-        return false;
+	status = pjsip_inv_send_msg ( call->getInvSession(), tdata );
+	if ( status != PJ_SUCCESS )
+		return false;
 
-    call->getInvSession()->mod_data[getModId()] = NULL;
+	call->getInvSession()->mod_data[getModId() ] = NULL;
 
-    terminateOneCall(id);
-    return true;
+	terminateOneCall ( id );
+	return true;
 }
 
-    void 
-SIPVoIPLink::setRecording(const CallID& id)
+void
+SIPVoIPLink::setRecording ( const CallID& id )
 {
-    SIPCall* call = getSIPCall(id);
+	SIPCall* call = getSIPCall ( id );
 
-    if(call)
-        call->setRecording();
+	if ( call )
+		call->setRecording();
 
-    // _audiortp->setRecording();
+	// _audiortp->setRecording();
 }
 
-    bool
-SIPVoIPLink::isRecording(const CallID& id)
+bool
+SIPVoIPLink::isRecording ( const CallID& id )
 {
-    SIPCall* call = getSIPCall(id);
-    _debug("call->isRecording() %i \n",call->isRecording());
-    if(call)
-        return call->isRecording();
-    else 
-        return false;
+	SIPCall* call = getSIPCall ( id );
+	_debug ( "call->isRecording() %i \n",call->isRecording() );
+	if ( call )
+		return call->isRecording();
+	else
+		return false;
 }
 
 
-    std::string 
+std::string
 SIPVoIPLink::getCurrentCodecName()
 {
 
-    SIPCall *call;
-    AudioCodec *ac = NULL;
-    std::string name = "";
-    
-    call = getSIPCall(Manager::instance().getCurrentCallId());  
-    if (call)
-        ac = call->getLocalSDP()->get_session_media();
+	SIPCall *call;
+	AudioCodec *ac = NULL;
+	std::string name = "";
+
+	call = getSIPCall ( Manager::instance().getCurrentCallId() );
+	if ( call )
+		ac = call->getLocalSDP()->get_session_media();
+
+	if ( ac )
+		name = ac->getCodecName();
+
+	return name;
+}
+
+bool
+SIPVoIPLink::carryingDTMFdigits ( const CallID& id, char code )
+{
+
+	SIPCall *call;
+	int duration;
+	const int body_len = 1000;
+	char *dtmf_body;
+	pj_status_t status;
+	pjsip_tx_data *tdata;
+	pj_str_t methodName, content;
+	pjsip_method method;
+	pjsip_media_type ctype;
+
+	call = getSIPCall ( id );
+
+	if ( call==0 )
+	{
+		_debug ( "Call doesn't exist\n" );
+		return false;
+	}
+
+	duration = Manager::instance().getConfigInt ( SIGNALISATION, PULSE_LENGTH );
+	dtmf_body = new char[body_len];
+
+	snprintf ( dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration );
+
+	pj_strdup2 ( _pool, &methodName, "INFO" );
+	pjsip_method_init_np ( &method, &methodName );
+
+	/* Create request message. */
+	status = pjsip_dlg_create_request ( call->getInvSession()->dlg, &method, -1, &tdata );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to create INFO request -- %d\n", status );
+		return false;
+	}
+
+	/* Get MIME type */
+	pj_strdup2 ( _pool, &ctype.type, "application" );
+	pj_strdup2 ( _pool, &ctype.subtype, "dtmf-relay" );
+
+	/* Create "application/dtmf-relay" message body. */
+	pj_strdup2 ( _pool, &content, dtmf_body );
+	tdata->msg->body = pjsip_msg_body_create ( tdata->pool, &ctype.type, &ctype.subtype, &content );
+	if ( tdata->msg->body == NULL )
+	{
+		_debug ( "UserAgent: Unable to create msg body!\n" );
+		pjsip_tx_data_dec_ref ( tdata );
+		return false;
+	}
+
+	/* Send the request. */
+	status = pjsip_dlg_send_request ( call->getInvSession()->dlg, tdata, getModId(), NULL );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unable to send MESSAGE request -- %d\n", status );
+		return false;
+	}
+
+	return true;
+}
+
+bool
+SIPVoIPLink::SIPOutgoingInvite ( SIPCall* call )
+{
+	// If no SIP proxy setting for direct call with only IP address
+	if ( !SIPStartCall ( call, "" ) )
+	{
+		_debug ( "! SIP Failure: call not started\n" );
+		return false;
+	}
+	return true;
+}
+
+bool
+SIPVoIPLink::SIPStartCall ( SIPCall* call, const std::string& subject UNUSED )
+{
+	std::string strTo, strFrom;
+	pj_status_t status;
+	pjsip_dialog *dialog;
+	pjsip_tx_data *tdata;
+	pj_str_t from, to, contact;
+	AccountID id;
+	SIPAccount *account;
+	pjsip_inv_session *inv;
+
+	if ( !call )
+		return false;
+
+	id = Manager::instance().getAccountFromCall ( call->getCallId() );
+	// Get the basic information about the callee account
+	account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( id ) );
+
+	strTo = getSipTo ( call->getPeerNumber(), account->getHostname() );
+	_debug ( "            To: %s\n", strTo.data() );
+
+	// Generate the from URI
+	strFrom = "sip:" + account->getUsername() + "@" + account->getHostname();
+
+	// pjsip need the from and to information in pj_str_t format
+	pj_strdup2 ( _pool, &from, strFrom.data() );
+	pj_strdup2 ( _pool, &to, strTo.data() );
+	pj_strdup2 ( _pool, &contact, account->getContact().data() );
+
+	//_debug("%s %s %s\n", from.ptr, contact.ptr, to.ptr);
+	// create the dialog (UAC)
+	status = pjsip_dlg_create_uac ( pjsip_ua_instance(), &from,
+	                                &contact,
+	                                &to,
+	                                NULL,
+	                                &dialog );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UAC creation failed\n" );
+		return false;
+	}
+
+	// Create the invite session for this call
+	status = pjsip_inv_create_uac ( dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false );
+
+	// Set auth information
+	pjsip_auth_clt_set_credentials ( &dialog->auth_sess, 1, account->getCredInfo() );
+
+	// Associate current call in the invite session
+	inv->mod_data[getModId() ] = call;
+
+	status = pjsip_inv_invite ( inv, &tdata );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false );
+
+	// Associate current invite session in the call
+	call->setInvSession ( inv );
+
+	status = pjsip_inv_send_msg ( inv, tdata );
+	if ( status != PJ_SUCCESS )
+	{
+		return false;
+	}
+
+	return true;
+}
+
+std::string SIPVoIPLink::getSipTo ( const std::string& to_url, std::string hostname )
+{
+	// Form the From header field basis on configuration panel
+	//bool isRegistered = (_eXosipRegID == EXOSIP_ERROR_STD) ? false : true;
+
+	// add a @host if we are registered and there is no one inside the url
+	if ( to_url.find ( "@" ) == std::string::npos )  // && isRegistered) {
+	{
+		if ( !hostname.empty() )
+		{
+			return SIPToHeader ( to_url + "@" + hostname );
+		}
+	}
+	return SIPToHeader ( to_url );
+}
+
+std::string SIPVoIPLink::SIPToHeader ( const std::string& to )
+{
+	if ( to.find ( "sip:" ) == std::string::npos )
+	{
+		return ( "sip:" + to );
+	}
+	else
+	{
+		return to;
+	}
+}
+
+bool
+SIPVoIPLink::SIPCheckUrl ( const std::string& url UNUSED )
+{
+	return true;
+}
+
+void
+SIPVoIPLink::SIPCallServerFailure ( SIPCall *call )
+{
+	//if (!event->response) { return; }
+	//switch(event->response->status_code) {
+	//case SIP_SERVICE_UNAVAILABLE: // 500
+	//case SIP_BUSY_EVRYWHERE:     // 600
+	//case SIP_DECLINE:             // 603
+	//SIPCall* call = findSIPCallWithCid(event->cid);
+	if ( call != 0 )
+	{
+		_debug ( "Server error!\n" );
+		CallID id = call->getCallId();
+		Manager::instance().callFailure ( id );
+		terminateOneCall ( id );
+		removeCall ( id );
+	}
+	//break;
+	//}
+}
+
+void
+SIPVoIPLink::SIPCallClosed ( SIPCall *call )
+{
+
+
+	// it was without did before
+	//SIPCall* call = findSIPCallWithCid(event->cid);
+	if ( !call ) { return; }
+
+	CallID id = call->getCallId();
+	//call->setDid(event->did);
+	if ( Manager::instance().isCurrentCall ( id ) )
+	{
+		call->setAudioStart ( false );
+		_debug ( "* SIP Info: Stopping AudioRTP when closing\n" );
+		_audiortp->closeRtpSession();
+	}
+	_debug ( "After close RTP\n" );
+	Manager::instance().peerHungupCall ( id );
+	terminateOneCall ( id );
+	removeCall ( id );
+	_debug ( "After remove call ID\n" );
+}
+
+void
+SIPVoIPLink::SIPCallReleased ( SIPCall *call )
+{
+	// do cleanup if exists
+	// only cid because did is always 0 in these case..
+	//SIPCall* call = findSIPCallWithCid(event->cid);
+	if ( !call ) { return; }
+
+	// if we are here.. something when wrong before...
+	_debug ( "SIP call release\n" );
+	CallID id = call->getCallId();
+	Manager::instance().callFailure ( id );
+	terminateOneCall ( id );
+	removeCall ( id );
+}
+
+
+void
+SIPVoIPLink::SIPCallAnswered ( SIPCall *call, pjsip_rx_data *rdata )
+{
+
+	pjmedia_sdp_session *r_sdp;
+
+	if ( !call )
+	{
+		_debug ( "! SIP Failure: unknown call\n" );
+		return;
+	}
+
+	if ( call->getConnectionState() != Call::Connected )
+	{
+		_debug ( "Get remote SDP from offer\n" );
+		get_remote_sdp_from_offer ( rdata, &r_sdp );
+		if ( r_sdp==NULL )
+		{
+			_debug ( "SIP Failure: no remote sdp session\n" );
+			return;
+		}
+		_debug ( "Get remote media information from offer\n" );
+		call->getLocalSDP()->fetch_media_transport_info_from_remote_sdp ( r_sdp );
+
+		_debug ( "Update call state , id = %s\n", call->getCallId().c_str() );
+		call->setConnectionState ( Call::Connected );
+		call->setState ( Call::Active );
+
+		Manager::instance().peerAnsweredCall ( call->getCallId() );
+		if ( Manager::instance().isCurrentCall ( call->getCallId() ) )
+		{
+			_debug ( "* SIP Info: Starting AudioRTP when answering\n" );
+			if ( _audiortp->createNewSession ( call ) < 0 )
+			{
+				_debug ( "RTP Failure: unable to create new session\n" );
+			}
+			else
+			{
+				call->setAudioStart ( true );
+			}
+		}
+	}
+	else
+	{
+		_debug ( "* SIP Info: Answering call (on/off hold to send ACK)\n" );
+	}
+}
+
+
+SIPCall*
+SIPVoIPLink::getSIPCall ( const CallID& id )
+{
+	Call* call = getCall ( id );
+	if ( call )
+	{
+		return dynamic_cast<SIPCall*> ( call );
+	}
+	return NULL;
+}
+
+
+void SIPVoIPLink::setStunServer ( const std::string &server )
+{
+	if ( server != "" )
+	{
+
+		useStun ( true );
+		_stunServer = server;
+	}
+	else
+	{
+		useStun ( false );
+		_stunServer = std::string ( "" );
+	}
+}
+
+bool SIPVoIPLink::new_ip_to_ip_call ( const CallID& id, const std::string& to )
+{
+	SIPCall *call;
+	pj_status_t status;
+	std::string uri_from, uri_to, hostname;
+	std::ostringstream uri_contact;
+	pj_str_t from, str_to, contact;
+	pjsip_dialog *dialog;
+	pjsip_inv_session *inv;
+	pjsip_tx_data *tdata;
+
+	/* Create the call */
+	call = new SIPCall ( id, Call::Outgoing, _pool );
+
+	if ( call )
+	{
+
+		call->setCallConfiguration ( Call::IPtoIP );
+		call->setPeerNumber ( getSipTo ( to, getLocalIPAddress() ) );
+
+		// Generate the from URI
+		hostname = pj_gethostname()->ptr;
+		uri_from = "sip:" + hostname + "@" + getLocalIPAddress() ;
+
+		// Generate the from URI
+		uri_to = "sip:" + to.substr ( 4, to.length() );
+
+		_debug ( "get local ip address: %s \n", getLocalIPAddress().c_str() );
+		// Generate the to URI
+		setCallAudioLocal ( call, getLocalIPAddress(), useStun(), getStunServer() );
+
+		call->initRecFileName();
+
+		// Building the local SDP offer
+		call->getLocalSDP()->set_ip_address ( getLocalIP() );
+		call->getLocalSDP()->create_initial_offer();
+
+		// Generate the contact URI
+		// uri_contact << "<" << uri_from << ":" << call->getLocalSDP()->get_local_extern_audio_port() << ">";
+		uri_contact << "<" << uri_from << ":" << _localExternPort << ">";
+
+		// pjsip need the from and to information in pj_str_t format
+		pj_strdup2 ( _pool, &from, uri_from.data() );
+		pj_strdup2 ( _pool, &str_to, uri_to.data() );
+		pj_strdup2 ( _pool, &contact, uri_contact.str().data() );
+
+		// create the dialog (UAC)
+		status = pjsip_dlg_create_uac ( pjsip_ua_instance(), &from, &contact, &str_to, NULL, &dialog );
+		PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false );
+
+		// Create the invite session for this call
+		status = pjsip_inv_create_uac ( dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv );
+		PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false );
+
+		// Associate current call in the invite session
+		inv->mod_data[getModId() ] = call;
+
+		status = pjsip_inv_invite ( inv, &tdata );
+		PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false );
+
+		// Associate current invite session in the call
+		call->setInvSession ( inv );
+
+		status = pjsip_inv_send_msg ( inv, tdata );
+		if ( status != PJ_SUCCESS )
+		{
+			delete call; call = 0;
+			return false;
+		}
+
+		call->setConnectionState ( Call::Progressing );
+		call->setState ( Call::Active );
+		addCall ( call );
+
+		return true;
+	}
+	else
+		return false;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Private functions
+///////////////////////////////////////////////////////////////////////////////
+
+
+bool get_dns_server_addresses ( std::vector<std::string> *servers )
+{
+
+	int server_count, i;
+	std::vector<std::string> nameservers;
+	struct  sockaddr_in current_server;
+	in_addr address;
+
+	// Read configuration files
+	if ( res_init () != 0 )
+	{
+		_debug ( "Resolver initialization failed\n" );
+		return false;
+	}
+
+	server_count = _res.nscount;
+	for ( i=0; i<server_count; i++ )
+	{
+		current_server = ( struct  sockaddr_in ) _res.nsaddr_list[i];
+		address = current_server.sin_addr;
+		nameservers.push_back ( inet_ntoa ( address ) );
+	}
+
+	//nameservers.push_back ("192.168.50.3");
+	*servers = nameservers;
+
+	return true;
+}
+
+pj_status_t SIPVoIPLink::enable_dns_srv_resolver ( pjsip_endpoint *endpt, pj_dns_resolver **p_resv )
+{
+
+	pj_status_t status;
+	pj_dns_resolver *resv;
+	std::vector <std::string> dns_servers;
+	pj_uint16_t port = 5353;
+	pjsip_resolver_t *res;
+	int scount, i;
+
+	// Create the DNS resolver instance
+	status = pjsip_endpt_create_resolver ( endpt, &resv );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "Error creating the DNS resolver instance\n" );
+		return status;
+	}
+
+	if ( !get_dns_server_addresses ( &dns_servers ) )
+	{
+		_debug ( "Error  while fetching DNS information\n" );
+		return -1;
+	}
+
+	// Build the nameservers list needed by pjsip
+	scount = dns_servers.size ();
+	pj_str_t nameservers[scount];
+
+	for ( i = 0; i<scount; i++ )
+	{
+		nameservers[i] = pj_str ( ( char* ) dns_servers[i].c_str() );
+	}
+
+	// Update the name servers for the DNS resolver
+	status = pj_dns_resolver_set_ns ( resv, scount, nameservers, NULL );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "Error updating the name servers for the DNS resolver\n" );
+		return status;
+	}
+
+	// Set the DNS resolver instance of the SIP resolver engine
+	status = pjsip_endpt_set_resolver ( endpt, resv );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "Error setting the DNS resolver instance of the SIP resolver engine\n" );
+		return status;
+	}
+
+	*p_resv = resv;
+
+	return PJ_SUCCESS;
+
+}
+
+
+bool SIPVoIPLink::pjsip_init()
+{
+	pj_status_t status;
+	int errPjsip = 0;
+	int port;
+	pjsip_inv_callback inv_cb;
+	pj_str_t accepted;
+	std::string name_mod;
+	bool useStun;
+	validStunServer = true;
+	pj_dns_resolver *p_resv;
+
+	name_mod = "sflphone";
+
+	// Init PJLIB: must be called before any call to the pjsip library
+	status = pj_init();
+	// Use pjsip macros for sanity check
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Init PJLIB-UTIL library
+	status = pjlib_util_init();
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Set the pjsip log level
+	pj_log_set_level ( PJ_LOG_LEVEL );
+
+	// Init PJNATH
+	status = pjnath_init();
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Create a pool factory to allocate memory
+	pj_caching_pool_init ( &_cp, &pj_pool_factory_default_policy, 0 );
+
+	// Create memory pool for application.
+	_pool = pj_pool_create ( &_cp.factory, "sflphone", 4000, 4000, NULL );
+
+	if ( !_pool )
+	{
+		_debug ( "UserAgent: Could not initialize memory pool\n" );
+		return PJ_ENOMEM;
+	}
+
+	// Create the SIP endpoint
+	status = pjsip_endpt_create ( &_cp.factory, pj_gethostname()->ptr, &_endpt );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	/* Start resolving STUN server */
+	// if we useStun and we failed to receive something on port 5060, we try a random port
+	// If use STUN server, firewall address setup
+	if ( !loadSIPLocalIP() )
+	{
+		_debug ( "UserAgent: Unable to determine network capabilities\n" );
+		return false;
+	}
+
+	port = _regPort;
+
+	/* Retrieve the STUN configuration */
+	useStun = Manager::instance().getConfigInt ( SIGNALISATION, SIP_USE_STUN );
+	this->setStunServer ( Manager::instance().getConfigString ( SIGNALISATION, SIP_STUN_SERVER ) );
+	this->useStun ( useStun!=0 ? true : false );
+
+	if ( useStun && !Manager::instance().behindNat ( getStunServer(), port ) )
+	{
+		port = RANDOM_SIP_PORT;
+		if ( !Manager::instance().behindNat ( getStunServer(), port ) )
+		{
+			_debug ( "UserAgent: Unable to check NAT setting\n" );
+			validStunServer = false;
+			return false; // hoho we can't use the random sip port too...
+		}
+	}
+
+	_localPort = port;
+	if ( useStun )
+	{
+		// set by last behindNat() call (ish)...
+		stunServerResolve();
+		_localExternAddress = Manager::instance().getFirewallAddress();
+		_localExternPort = Manager::instance().getFirewallPort();
+		errPjsip = createUDPServer();
+		if ( errPjsip != 0 )
+		{
+			_debug ( "UserAgent: Could not initialize SIP listener on port %d\n", port );
+			return errPjsip;
+		}
+	}
+	else
+	{
+		_localExternAddress = _localIPAddress;
+		_localExternPort = _localPort;
+		errPjsip = createUDPServer();
+		if ( errPjsip != 0 )
+		{
+			_debug ( "UserAgent: Could not initialize SIP listener on port %d\n", _localExternPort );
+			_localExternPort = _localPort = RANDOM_SIP_PORT;
+			_debug ( "UserAgent: Try to initialize SIP listener on port %d\n", _localExternPort );
+			errPjsip = createUDPServer();
+			if ( errPjsip != 0 )
+			{
+				_debug ( "UserAgent: Fail to initialize SIP listener on port %d\n", _localExternPort );
+				return errPjsip;
+			}
+		}
+	}
+
+	_debug ( "UserAgent: SIP Init -- listening on port %d\n", _localExternPort );
+
+	// Initialize transaction layer
+	status = pjsip_tsx_layer_init_module ( _endpt );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Initialize UA layer module
+	status = pjsip_ua_init_module ( _endpt, NULL );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Initialize Replaces support. See the Replaces specification in RFC 3891
+	status = pjsip_replaces_init_module ( _endpt );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Initialize 100rel support
+	status = pjsip_100rel_init_module ( _endpt );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Initialize and register sflphone module
+	_mod_ua.name = pj_str ( ( char* ) name_mod.c_str() );
+	_mod_ua.id = -1;
+	_mod_ua.priority = PJSIP_MOD_PRIORITY_APPLICATION;
+	_mod_ua.on_rx_request = &mod_on_rx_request;
+	_mod_ua.on_rx_response = &mod_on_rx_response;
+
+	status = pjsip_endpt_register_module ( _endpt, &_mod_ua );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Init the event subscription module.
+	// It extends PJSIP by supporting SUBSCRIBE and NOTIFY methods
+	status = pjsip_evsub_init_module ( _endpt );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Init xfer/REFER module
+	status = pjsip_xfer_init_module ( _endpt );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	status = enable_dns_srv_resolver (_endpt, &p_resv);
+	PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
+
+	// Init the callback for INVITE session:
+	pj_bzero ( &inv_cb, sizeof ( inv_cb ) );
+
+	inv_cb.on_state_changed = &call_on_state_changed;
+	inv_cb.on_new_session = &call_on_forked;
+	inv_cb.on_media_update = &call_on_media_update;
+	inv_cb.on_tsx_state_changed = &call_on_tsx_changed;
+	inv_cb.on_rx_offer = &on_rx_offer;
+
+	// Initialize session invite module
+	status = pjsip_inv_usage_init ( _endpt, &inv_cb );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	_debug ( "UserAgent: VOIP callbacks initialized\n" );
 
-    if (ac)
-        name = ac->getCodecName();
+	// Add endpoint capabilities (INFO, OPTIONS, etc) for this UA
+	pj_str_t allowed[] = { { ( char* ) "INFO", 4}, { ( char* ) "REGISTER", 8}, { ( char* ) "OPTIONS", 7} }; //  //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6}
+	accepted = pj_str ( ( char* ) "application/sdp" );
 
-    return name;
+	// Register supported methods
+	pjsip_endpt_add_capability ( _endpt, &_mod_ua, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE ( allowed ), allowed );
+
+	// Register "application/sdp" in ACCEPT header
+	pjsip_endpt_add_capability ( _endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &accepted );
+
+	_debug ( "UserAgent: pjsip version %s for %s initialized\n", pj_get_version(), PJ_OS_NAME );
+
+	// Create the secondary thread to poll sip events
+	_evThread->start();
+
+	/* Done! */
+	return PJ_SUCCESS;
 }
 
-    bool 
-SIPVoIPLink::carryingDTMFdigits(const CallID& id, char code)
+pj_status_t SIPVoIPLink::stunServerResolve ( void )
 {
+	pj_str_t stun_adr;
+	pj_hostent he;
+	pj_stun_config stunCfg;
+	pj_status_t stun_status;
+	pj_sockaddr stun_srv;
+	size_t pos;
+	std::string serverName, serverPort;
+	int nPort;
+	std::string stun_server;
+
+	stun_server = getStunServer();
+
+	// Initialize STUN configuration
+	pj_stun_config_init ( &stunCfg, &_cp.factory, 0, pjsip_endpt_get_ioqueue ( _endpt ), pjsip_endpt_get_timer_heap ( _endpt ) );
+
+	stun_status = PJ_EPENDING;
+
+	// Init STUN socket
+	pos = stun_server.find ( ':' );
+	if ( pos == std::string::npos )
+	{
+		pj_strdup2 ( _pool, &stun_adr, stun_server.data() );
+		stun_status = pj_sockaddr_in_init ( &stun_srv.ipv4, &stun_adr, ( pj_uint16_t ) 3478 );
+	}
+	else
+	{
+		serverName = stun_server.substr ( 0, pos );
+		serverPort = stun_server.substr ( pos + 1 );
+		nPort = atoi ( serverPort.data() );
+		pj_strdup2 ( _pool, &stun_adr, serverName.data() );
+		stun_status = pj_sockaddr_in_init ( &stun_srv.ipv4, &stun_adr, ( pj_uint16_t ) nPort );
+	}
+
+	if ( stun_status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: Unresolved stun server!\n" );
+		stun_status = pj_gethostbyname ( &stun_adr, &he );
+
+		if ( stun_status == PJ_SUCCESS )
+		{
+			pj_sockaddr_in_init ( &stun_srv.ipv4, NULL, 0 );
+			stun_srv.ipv4.sin_addr = * ( pj_in_addr* ) he.h_addr;
+			stun_srv.ipv4.sin_port = pj_htons ( ( pj_uint16_t ) 3478 );
+		}
+	}
+
+	return stun_status;
+}
+
+int SIPVoIPLink::createUDPServer ( void )
+{
+
+	pj_status_t status;
+	pj_sockaddr_in bound_addr;
+	pjsip_host_port a_name;
+	char tmpIP[32];
+	pj_sock_t sock;
+
+
+	// Init bound address to ANY
+	pj_memset ( &bound_addr, 0, sizeof ( bound_addr ) );
 
-    SIPCall *call;
-    int duration;
-    const int body_len = 1000;
-    char *dtmf_body;
-    pj_status_t status;
-    pjsip_tx_data *tdata;
-    pj_str_t methodName, content;
-    pjsip_method method;
-    pjsip_media_type ctype;
-
-    call = getSIPCall(id);
-
-    if (call==0) { 
-        _debug("Call doesn't exist\n"); 
-        return false; 
-    }
-
-    duration = Manager::instance().getConfigInt(SIGNALISATION, PULSE_LENGTH);
-    dtmf_body = new char[body_len];
-
-    snprintf(dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration);
 
-    pj_strdup2(_pool, &methodName, "INFO");
-    pjsip_method_init_np(&method, &methodName);
+	bound_addr.sin_addr.s_addr = pj_htonl ( PJ_INADDR_ANY );
+	bound_addr.sin_port = pj_htons ( ( pj_uint16_t ) _localPort );
+	bound_addr.sin_family = PJ_AF_INET;
+	pj_bzero ( bound_addr.sin_zero, sizeof ( bound_addr.sin_zero ) );
+
+	// Create UDP-Server (default port: 5060)
+	strcpy ( tmpIP, _localExternAddress.data() );
+	pj_strdup2 ( _pool, &a_name.host, tmpIP );
+	a_name.port = ( pj_uint16_t ) _localExternPort;
+
+
+	status = pjsip_udp_transport_start ( _endpt, &bound_addr, &a_name, 1, NULL );
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "UserAgent: (%d) Unable to start UDP transport!\n", status );
+		return -1;
+	}
+	else
+	{
+		_debug ( "UserAgent: UDP server listening on port %d\n", _localExternPort );
+	}
+
+
+	_debug ( "Transport initialized successfully! \n" );
+	return PJ_SUCCESS;
+}
 
-    /* Create request message. */
-    status = pjsip_dlg_create_request( call->getInvSession()->dlg, &method, -1, &tdata);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to create INFO request -- %d\n", status);
-        return false;
-    }
 
-    /* Get MIME type */
-    pj_strdup2(_pool, &ctype.type, "application");
-    pj_strdup2(_pool, &ctype.subtype, "dtmf-relay");
 
-    /* Create "application/dtmf-relay" message body. */
-    pj_strdup2(_pool, &content, dtmf_body);
-    tdata->msg->body = pjsip_msg_body_create( tdata->pool, &ctype.type, &ctype.subtype, &content);
-    if (tdata->msg->body == NULL) {
-        _debug("UserAgent: Unable to create msg body!\n");
-        pjsip_tx_data_dec_ref(tdata);
-        return false;
-    }
 
-    /* Send the request. */
-    status = pjsip_dlg_send_request( call->getInvSession()->dlg, tdata, getModId(), NULL);
-    if (status != PJ_SUCCESS) {
-        _debug("UserAgent: Unable to send MESSAGE request -- %d\n", status);
-        return false;
-    }
-
-    return true;
-}
-
-    bool
-SIPVoIPLink::SIPOutgoingInvite(SIPCall* call) 
-{
-    // If no SIP proxy setting for direct call with only IP address
-    if (!SIPStartCall(call, "")) {
-        _debug("! SIP Failure: call not started\n");
-        return false;
-    }
-    return true;
-}
-
-    bool
-SIPVoIPLink::SIPStartCall(SIPCall* call, const std::string& subject UNUSED) 
-{
-    std::string strTo, strFrom;
-    pj_status_t status;
-    pjsip_dialog *dialog;
-    pjsip_tx_data *tdata;
-    pj_str_t from, to, contact;
-    AccountID id;
-    SIPAccount *account;
-    pjsip_inv_session *inv;
-
-    if (!call) 
-        return false;
-
-    id = Manager::instance().getAccountFromCall(call->getCallId());
-    // Get the basic information about the callee account
-    account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(id));
-
-    strTo = getSipTo(call->getPeerNumber(), account->getHostname());
-    _debug("            To: %s\n", strTo.data());
-
-    // Generate the from URI
-    strFrom = "sip:" + account->getUsername() + "@" + account->getHostname();
-
-    // pjsip need the from and to information in pj_str_t format
-    pj_strdup2(_pool, &from, strFrom.data());
-    pj_strdup2(_pool, &to, strTo.data());
-    pj_strdup2(_pool, &contact, account->getContact().data());
-
-    //_debug("%s %s %s\n", from.ptr, contact.ptr, to.ptr);
-    // create the dialog (UAC)
-    status = pjsip_dlg_create_uac(pjsip_ua_instance(), &from,
-            &contact,
-            &to,
-            NULL,
-            &dialog);
-    if (status != PJ_SUCCESS){
-        _debug ("UAC creation failed\n");
-        return false;
-    }
-
-    // Create the invite session for this call
-    status = pjsip_inv_create_uac(dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv);
-    PJ_ASSERT_RETURN(status == PJ_SUCCESS, false);
-
-    // Set auth information
-    pjsip_auth_clt_set_credentials(&dialog->auth_sess, 1, account->getCredInfo());
-
-    // Associate current call in the invite session
-    inv->mod_data[getModId()] = call;
-
-    status = pjsip_inv_invite(inv, &tdata);
-    PJ_ASSERT_RETURN(status == PJ_SUCCESS, false);
-
-    // Associate current invite session in the call
-    call->setInvSession(inv);
-
-    status = pjsip_inv_send_msg(inv, tdata);
-    if(status != PJ_SUCCESS) {
-        return false;
-    }
-
-    return true;
-}
-
-std::string SIPVoIPLink::getSipTo(const std::string& to_url, std::string hostname) {
-    // Form the From header field basis on configuration panel
-    //bool isRegistered = (_eXosipRegID == EXOSIP_ERROR_STD) ? false : true;
-
-    // add a @host if we are registered and there is no one inside the url
-    if (to_url.find("@") == std::string::npos) {// && isRegistered) {
-        if(!hostname.empty()) {
-            return SIPToHeader(to_url + "@" + hostname);
-        }
-    }
-    return SIPToHeader(to_url);
-    }
-
-    std::string SIPVoIPLink::SIPToHeader(const std::string& to) 
-    {
-        if (to.find("sip:") == std::string::npos) {
-            return ("sip:" + to );
-        } else {
-            return to;
-        }
-    }
-
-    bool
-        SIPVoIPLink::SIPCheckUrl(const std::string& url UNUSED)
-        {
-            return true;
-        }
-
-    void
-        SIPVoIPLink::SIPCallServerFailure(SIPCall *call) 
-        {
-            //if (!event->response) { return; }
-            //switch(event->response->status_code) {
-            //case SIP_SERVICE_UNAVAILABLE: // 500
-            //case SIP_BUSY_EVRYWHERE:     // 600
-            //case SIP_DECLINE:             // 603
-            //SIPCall* call = findSIPCallWithCid(event->cid);
-            if (call != 0) {
-                _debug("Server error!\n");
-                CallID id = call->getCallId();
-                Manager::instance().callFailure(id);
-                terminateOneCall(id);
-                removeCall(id);
-            }
-            //break;
-            //}
-        }
-
-    void
-        SIPVoIPLink::SIPCallClosed(SIPCall *call) 
-        {
-
-            
-            // it was without did before
-            //SIPCall* call = findSIPCallWithCid(event->cid);
-            if (!call) { return; }
-
-            CallID id = call->getCallId();
-            //call->setDid(event->did);
-            if (Manager::instance().isCurrentCall(id)) {
-                call->setAudioStart(false);
-                _debug("* SIP Info: Stopping AudioRTP when closing\n");
-                _audiortp->closeRtpSession();
-            }
-            _debug("After close RTP\n");
-            Manager::instance().peerHungupCall(id);
-            terminateOneCall(id);
-            removeCall(id);
-            _debug("After remove call ID\n");
-        }
-
-    void
-        SIPVoIPLink::SIPCallReleased(SIPCall *call)
-        {
-            // do cleanup if exists
-            // only cid because did is always 0 in these case..
-            //SIPCall* call = findSIPCallWithCid(event->cid);
-            if (!call) { return; }
-
-            // if we are here.. something when wrong before...
-            _debug("SIP call release\n");
-            CallID id = call->getCallId();
-            Manager::instance().callFailure(id);
-            terminateOneCall(id);
-            removeCall(id);
-        }
-
-
-    void
-        SIPVoIPLink::SIPCallAnswered(SIPCall *call, pjsip_rx_data *rdata)
-        {
-
-            pjmedia_sdp_session *r_sdp;    
-
-            if (!call) {
-                _debug("! SIP Failure: unknown call\n");
-                return;
-            }
-
-            if (call->getConnectionState() != Call::Connected) {
-                _debug ("Get remote SDP from offer\n");
-                get_remote_sdp_from_offer (rdata, &r_sdp);
-                if (r_sdp==NULL) {
-                    _debug("SIP Failure: no remote sdp session\n");
-                    return;
-                }
-                _debug ("Get remote media information from offer\n");
-                call->getLocalSDP()->fetch_media_transport_info_from_remote_sdp (r_sdp);
-
-                _debug ("Update call state , id = %s\n", call->getCallId().c_str());
-                call->setConnectionState(Call::Connected);
-                call->setState(Call::Active);
-
-                Manager::instance().peerAnsweredCall(call->getCallId());
-                if (Manager::instance().isCurrentCall(call->getCallId())) {
-                    _debug("* SIP Info: Starting AudioRTP when answering\n");
-                    if ( _audiortp->createNewSession(call) < 0) {
-                        _debug("RTP Failure: unable to create new session\n");
-                    } else {
-                        call->setAudioStart(true);
-                    }
-                }
-            } else {
-                _debug("* SIP Info: Answering call (on/off hold to send ACK)\n");
-            }
-        }
-
-
-    SIPCall*
-        SIPVoIPLink::getSIPCall(const CallID& id) 
-        {
-            Call* call = getCall(id);
-            if (call) {
-                return dynamic_cast<SIPCall*>(call);
-            }
-            return NULL;
-        }
-
-
-    void SIPVoIPLink::setStunServer( const std::string &server )
-    {
-        if(server != "") {
-
-            useStun(true);
-            _stunServer = server;
-        } else {
-            useStun(false);
-            _stunServer = std::string("");
-        }
-    }
-
-    bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) {
-        SIPCall *call;
-        pj_status_t status;
-        std::string uri_from, uri_to, hostname;
-        std::ostringstream uri_contact;
-        pj_str_t from, str_to, contact;
-        pjsip_dialog *dialog;
-        pjsip_inv_session *inv;
-        pjsip_tx_data *tdata;
-
-        /* Create the call */
-        call = new SIPCall(id, Call::Outgoing, _pool);
-
-        if (call) {
-        
-            call->setCallConfiguration (Call::IPtoIP);
-            call->setPeerNumber(getSipTo(to, getLocalIPAddress()));
-
-            // Generate the from URI
-            hostname = pj_gethostname()->ptr;
-            uri_from = "sip:" + hostname + "@" + getLocalIPAddress() ;
-
-            // Generate the from URI
-            uri_to = "sip:" + to.substr (4, to.length());
-
-            _debug("get local ip address: %s \n", getLocalIPAddress().c_str());
-            // Generate the to URI
-            setCallAudioLocal(call, getLocalIPAddress(), useStun(), getStunServer());
-
-            call->initRecFileName();
-
-            // Building the local SDP offer
-            call->getLocalSDP()->set_ip_address(getLocalIP());
-            call->getLocalSDP()->create_initial_offer();
-
-            // Generate the contact URI
-            // uri_contact << "<" << uri_from << ":" << call->getLocalSDP()->get_local_extern_audio_port() << ">";
-            uri_contact << "<" << uri_from << ":" << _localExternPort << ">";
-
-            // pjsip need the from and to information in pj_str_t format
-            pj_strdup2(_pool, &from, uri_from.data());
-            pj_strdup2(_pool, &str_to, uri_to.data());
-            pj_strdup2(_pool, &contact, uri_contact.str().data());
-
-            // create the dialog (UAC)
-            status = pjsip_dlg_create_uac(pjsip_ua_instance(), &from, &contact, &str_to, NULL, &dialog);
-            PJ_ASSERT_RETURN(status == PJ_SUCCESS, false);
-
-            // Create the invite session for this call
-            status = pjsip_inv_create_uac(dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv);
-            PJ_ASSERT_RETURN(status == PJ_SUCCESS, false);
-
-            // Associate current call in the invite session
-            inv->mod_data[getModId()] = call;
-
-            status = pjsip_inv_invite(inv, &tdata);
-            PJ_ASSERT_RETURN(status == PJ_SUCCESS, false);
-
-            // Associate current invite session in the call
-            call->setInvSession(inv);
-
-            status = pjsip_inv_send_msg(inv, tdata);
-            if(status != PJ_SUCCESS) {
-                delete call; call = 0;
-                return false;
-            }
-    
-            call->setConnectionState(Call::Progressing);
-            call->setState(Call::Active);
-            addCall(call);
-            
-            return true;
-        }
-        else
-            return false;
-    } 
-
-
-    ///////////////////////////////////////////////////////////////////////////////
-    // Private functions
-    ///////////////////////////////////////////////////////////////////////////////
-
-
-    bool get_dns_server_addresses (std::vector<std::string> *servers) {
-    
-        int server_count, i;
-        std::vector<std::string> nameservers;
-        struct  sockaddr_in current_server;
-        in_addr address;
-
-        // Read configuration files
-        if (res_init () != 0)
-        {
-            _debug ("Resolver initialization failed\n");
-            return false;
-        }
-
-        server_count = _res.nscount;
-        for (i=0; i<server_count; i++) {
-            current_server = (struct  sockaddr_in)_res.nsaddr_list[i];
-            address = current_server.sin_addr;
-            nameservers.push_back (inet_ntoa (address));
-        }
-
-        //nameservers.push_back ("192.168.50.3");
-        *servers = nameservers;
-
-        return true;
-    }
-
-    pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_resolver **p_resv) {
-
-        pj_status_t status;
-        pj_dns_resolver *resv;
-        std::vector <std::string> dns_servers;
-        pj_uint16_t port = 5353;
-        pjsip_resolver_t *res;
-        int scount, i;
-
-        // Create the DNS resolver instance 
-        status = pjsip_endpt_create_resolver (endpt, &resv);
-        if (status != PJ_SUCCESS) {
-            _debug ("Error creating the DNS resolver instance\n");
-            return status;
-        }
-
-        if (!get_dns_server_addresses (&dns_servers))
-        {
-            _debug ("Error  while fetching DNS information\n");
-            return -1;
-        }
-
-        // Build the nameservers list needed by pjsip
-        scount = dns_servers.size ();
-        pj_str_t nameservers[scount];
-
-        for (i = 0; i<scount; i++) {
-            nameservers[i] = pj_str((char*)dns_servers[i].c_str());
-        }
-
-        // Update the name servers for the DNS resolver
-        status = pj_dns_resolver_set_ns (resv, scount, nameservers, NULL);
-        if (status != PJ_SUCCESS){
-            _debug ("Error updating the name servers for the DNS resolver\n");
-            return status;
-        }
-
-        // Set the DNS resolver instance of the SIP resolver engine
-        status = pjsip_endpt_set_resolver (endpt, resv);
-        if (status != PJ_SUCCESS){
-            _debug ("Error setting the DNS resolver instance of the SIP resolver engine\n");
-            return status;
-        }
-
-        *p_resv = resv;
-
-        return PJ_SUCCESS;
-    
-    }
-
-
-    bool SIPVoIPLink::pjsip_init()
-    {
-        pj_status_t status;
-        int errPjsip = 0;
-        int port;
-        pjsip_inv_callback inv_cb;
-        pj_str_t accepted;
-        std::string name_mod;
-        bool useStun;
-        validStunServer = true;
-        pj_dns_resolver *p_resv; 
-
-        name_mod = "sflphone";
-
-        // Init PJLIB: must be called before any call to the pjsip library
-        status = pj_init();
-        // Use pjsip macros for sanity check
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Init PJLIB-UTIL library 
-        status = pjlib_util_init();
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Set the pjsip log level
-        pj_log_set_level( PJ_LOG_LEVEL );
-
-        // Init PJNATH 
-        status = pjnath_init();
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Create a pool factory to allocate memory
-        pj_caching_pool_init(&_cp, &pj_pool_factory_default_policy, 0);
-
-        // Create memory pool for application. 
-        _pool = pj_pool_create(&_cp.factory, "sflphone", 4000, 4000, NULL);
-
-        if (!_pool) {
-            _debug("UserAgent: Could not initialize memory pool\n");
-            return PJ_ENOMEM;
-        }
-
-        // Create the SIP endpoint 
-        status = pjsip_endpt_create(&_cp.factory, pj_gethostname()->ptr, &_endpt);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        /* Start resolving STUN server */
-        // if we useStun and we failed to receive something on port 5060, we try a random port
-        // If use STUN server, firewall address setup
-        if (!loadSIPLocalIP()) {
-            _debug("UserAgent: Unable to determine network capabilities\n");
-            return false;
-        }
-
-        port = _regPort;
-
-        /* Retrieve the STUN configuration */
-        useStun = Manager::instance().getConfigInt( SIGNALISATION, SIP_USE_STUN );
-        this->setStunServer(Manager::instance().getConfigString( SIGNALISATION, SIP_STUN_SERVER ));
-        this->useStun( useStun!=0 ? true : false);
-
-        if (useStun && !Manager::instance().behindNat(getStunServer(), port)) {
-            port = RANDOM_SIP_PORT;
-            if (!Manager::instance().behindNat(getStunServer(), port)) {
-                _debug("UserAgent: Unable to check NAT setting\n");
-                validStunServer = false;		
-                return false; // hoho we can't use the random sip port too...
-            }
-        }
-
-        _localPort = port;
-        if (useStun) {
-            // set by last behindNat() call (ish)...
-            stunServerResolve();
-            _localExternAddress = Manager::instance().getFirewallAddress();
-            _localExternPort = Manager::instance().getFirewallPort();
-            errPjsip = createUDPServer();
-            if (errPjsip != 0) {
-                _debug("UserAgent: Could not initialize SIP listener on port %d\n", port);
-                return errPjsip;
-            }
-        } else {
-            _localExternAddress = _localIPAddress;
-            _localExternPort = _localPort;
-            errPjsip = createUDPServer();
-            if (errPjsip != 0) {
-                _debug("UserAgent: Could not initialize SIP listener on port %d\n", _localExternPort);
-                _localExternPort = _localPort = RANDOM_SIP_PORT;
-                _debug("UserAgent: Try to initialize SIP listener on port %d\n", _localExternPort);
-                errPjsip = createUDPServer();
-                if (errPjsip != 0) {
-                    _debug("UserAgent: Fail to initialize SIP listener on port %d\n", _localExternPort);
-                    return errPjsip;
-                }
-            }
-        }
-
-        _debug("UserAgent: SIP Init -- listening on port %d\n", _localExternPort);
-
-        // Initialize transaction layer
-        status = pjsip_tsx_layer_init_module(_endpt);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Initialize UA layer module
-        status = pjsip_ua_init_module(_endpt, NULL);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Initialize Replaces support. See the Replaces specification in RFC 3891
-        status = pjsip_replaces_init_module(_endpt);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Initialize 100rel support 
-        status = pjsip_100rel_init_module(_endpt);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Initialize and register sflphone module
-        _mod_ua.name = pj_str((char*)name_mod.c_str());
-        _mod_ua.id = -1;
-        _mod_ua.priority = PJSIP_MOD_PRIORITY_APPLICATION;
-        _mod_ua.on_rx_request = &mod_on_rx_request;
-        _mod_ua.on_rx_response = &mod_on_rx_response;
-
-        status = pjsip_endpt_register_module(_endpt, &_mod_ua);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Init the event subscription module.
-        // It extends PJSIP by supporting SUBSCRIBE and NOTIFY methods
-        status = pjsip_evsub_init_module(_endpt);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Init xfer/REFER module
-        status = pjsip_xfer_init_module(_endpt);
-        PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        //status = enable_dns_srv_resolver (_endpt, &p_resv);
-        //PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 );
-
-        // Init the callback for INVITE session: 
-        pj_bzero(&inv_cb, sizeof (inv_cb));
-
-        inv_cb.on_state_changed = &call_on_state_changed;
-        inv_cb.on_new_session = &call_on_forked;
-        inv_cb.on_media_update = &call_on_media_update;
-        inv_cb.on_tsx_state_changed = &call_on_tsx_changed;
-        inv_cb.on_rx_offer = &on_rx_offer;
-
-        // Initialize session invite module 
-        status = pjsip_inv_usage_init(_endpt, &inv_cb);
-        PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
-
-        _debug("UserAgent: VOIP callbacks initialized\n");
-
-        // Add endpoint capabilities (INFO, OPTIONS, etc) for this UA
-        pj_str_t allowed[] = { {(char*)"INFO", 4}, {(char*)"REGISTER", 8}, {(char*)"OPTIONS", 7} }; //  //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6} 
-        accepted = pj_str((char*)"application/sdp");
-
-        // Register supported methods
-        pjsip_endpt_add_capability(_endpt, &_mod_ua, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE(allowed), allowed);
-
-        // Register "application/sdp" in ACCEPT header
-        pjsip_endpt_add_capability(_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &accepted);
-
-        _debug("UserAgent: pjsip version %s for %s initialized\n", pj_get_version(), PJ_OS_NAME);
-
-        // Create the secondary thread to poll sip events
-        _evThread->start();
-
-        /* Done! */
-        return PJ_SUCCESS;
-    }
-
-    pj_status_t SIPVoIPLink::stunServerResolve( void )
-    {
-        pj_str_t stun_adr;
-        pj_hostent he;
-        pj_stun_config stunCfg;
-        pj_status_t stun_status;
-        pj_sockaddr stun_srv;
-        size_t pos;
-        std::string serverName, serverPort;
-        int nPort;
-        std::string stun_server;
-
-        stun_server = getStunServer();
-
-        // Initialize STUN configuration
-        pj_stun_config_init(&stunCfg, &_cp.factory, 0, pjsip_endpt_get_ioqueue(_endpt), pjsip_endpt_get_timer_heap(_endpt));
-
-        stun_status = PJ_EPENDING;
-
-        // Init STUN socket
-        pos = stun_server.find(':');
-        if(pos == std::string::npos) {
-            pj_strdup2(_pool, &stun_adr, stun_server.data());
-            stun_status = pj_sockaddr_in_init(&stun_srv.ipv4, &stun_adr, (pj_uint16_t) 3478);
-        } else {
-            serverName = stun_server.substr(0, pos);
-            serverPort = stun_server.substr(pos + 1);
-            nPort = atoi(serverPort.data());
-            pj_strdup2(_pool, &stun_adr, serverName.data());
-            stun_status = pj_sockaddr_in_init(&stun_srv.ipv4, &stun_adr, (pj_uint16_t) nPort);
-        }
-
-        if (stun_status != PJ_SUCCESS) {
-            _debug("UserAgent: Unresolved stun server!\n");
-            stun_status = pj_gethostbyname(&stun_adr, &he);
-
-            if (stun_status == PJ_SUCCESS) {
-                pj_sockaddr_in_init(&stun_srv.ipv4, NULL, 0);
-                stun_srv.ipv4.sin_addr = *(pj_in_addr*) he.h_addr;
-                stun_srv.ipv4.sin_port = pj_htons((pj_uint16_t) 3478);
-            }
-        }
-
-        return stun_status;
-    }
-
-    int SIPVoIPLink::createUDPServer( void ) 
-    {
-
-        pj_status_t status;
-        pj_sockaddr_in bound_addr;
-        pjsip_host_port a_name;
-        char tmpIP[32];
-        pj_sock_t sock;
-
-
-        // Init bound address to ANY
-        pj_memset(&bound_addr, 0, sizeof (bound_addr));
-
-
-        bound_addr.sin_addr.s_addr = pj_htonl(PJ_INADDR_ANY);
-        bound_addr.sin_port = pj_htons((pj_uint16_t) _localPort);
-        bound_addr.sin_family = PJ_AF_INET;
-        pj_bzero(bound_addr.sin_zero, sizeof(bound_addr.sin_zero));
-
-        // Create UDP-Server (default port: 5060)
-        strcpy(tmpIP, _localExternAddress.data());
-        pj_strdup2(_pool, &a_name.host, tmpIP);
-        a_name.port = (pj_uint16_t) _localExternPort; 
-
-
-        status = pjsip_udp_transport_start(_endpt, &bound_addr, &a_name, 1, NULL);   
-        if (status != PJ_SUCCESS) {
-            _debug("UserAgent: (%d) Unable to start UDP transport!\n", status);
-            return -1;
-        } else {
-            _debug("UserAgent: UDP server listening on port %d\n", _localExternPort);
-        }
-        
-        
-        _debug("Transport initialized successfully! \n");
-        return PJ_SUCCESS;
-    }
-
-    
-   
-    
-
-    bool SIPVoIPLink::loadSIPLocalIP() {
-
-        bool returnValue = true;
-
-        if (_localIPAddress == "127.0.0.1") {
-            pj_sockaddr ip_addr;
-            if (pj_gethostip(pj_AF_INET(), &ip_addr) != PJ_SUCCESS) {
-                // Update the registration state if no network capabilities found
-                _debug("UserAgent: Get host ip failed!\n");
-                returnValue = false;
-            } else {
-                _localIPAddress = std::string(pj_inet_ntoa(ip_addr.ipv4.sin_addr));
-                _debug("UserAgent: Checking network, setting local IP address to: %s\n", _localIPAddress.data());
-            }
-        }
-        return returnValue;
-    }
-
-    void SIPVoIPLink::busy_sleep(unsigned msec)
-    {
+
+bool SIPVoIPLink::loadSIPLocalIP()
+{
+
+	bool returnValue = true;
+
+	if ( _localIPAddress == "127.0.0.1" )
+	{
+		pj_sockaddr ip_addr;
+		if ( pj_gethostip ( pj_AF_INET(), &ip_addr ) != PJ_SUCCESS )
+		{
+			// Update the registration state if no network capabilities found
+			_debug ( "UserAgent: Get host ip failed!\n" );
+			returnValue = false;
+		}
+		else
+		{
+			_localIPAddress = std::string ( pj_inet_ntoa ( ip_addr.ipv4.sin_addr ) );
+			_debug ( "UserAgent: Checking network, setting local IP address to: %s\n", _localIPAddress.data() );
+		}
+	}
+	return returnValue;
+}
+
+void SIPVoIPLink::busy_sleep ( unsigned msec )
+{
 #if defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0
-        /* Ideally we shouldn't call pj_thread_sleep() and rather
-         * CActiveScheduler::WaitForAnyRequest() here, but that will
-         * drag in Symbian header and it doesn't look pretty.
-         */
-        pj_thread_sleep(msec);
+	/* Ideally we shouldn't call pj_thread_sleep() and rather
+	 * CActiveScheduler::WaitForAnyRequest() here, but that will
+	 * drag in Symbian header and it doesn't look pretty.
+	 */
+	pj_thread_sleep ( msec );
 #else
-        pj_time_val timeout, now, tv;
+	pj_time_val timeout, now, tv;
 
-        pj_gettimeofday(&timeout);
-        timeout.msec += msec;
-        pj_time_val_normalize(&timeout);
+	pj_gettimeofday ( &timeout );
+	timeout.msec += msec;
+	pj_time_val_normalize ( &timeout );
 
-        tv.sec = 0;
-        tv.msec = 10;
-        pj_time_val_normalize(&tv);
+	tv.sec = 0;
+	tv.msec = 10;
+	pj_time_val_normalize ( &tv );
 
-        do {
-            pjsip_endpt_handle_events(_endpt, &tv);
-            pj_gettimeofday(&now);
-        } while (PJ_TIME_VAL_LT(now, timeout));
+	do
+	{
+		pjsip_endpt_handle_events ( _endpt, &tv );
+		pj_gettimeofday ( &now );
+	}
+	while ( PJ_TIME_VAL_LT ( now, timeout ) );
 #endif
-    }    
-
-    bool SIPVoIPLink::pjsip_shutdown( void )
-    {
-        if (_endpt) {
-            _debug("UserAgent: Shutting down...\n");
-            busy_sleep(1000);
-        }
-
-        pj_thread_join( thread );
-        pj_thread_destroy( thread );
-        thread = NULL;
-
-        /* Destroy endpoint. */
-        if (_endpt) {
-            pjsip_endpt_destroy(_endpt);
-            _endpt = NULL;
-        }
-
-        /* Destroy pool and pool factory. */
-        if (_pool) {
-            pj_pool_release(_pool);
-            _pool = NULL;
-            pj_caching_pool_destroy(&_cp);
-        }
-
-        /* Shutdown PJLIB */
-        pj_shutdown();
-
-        /* Done. */    
-    }
-
-    int getModId(){
-        return _mod_ua.id;
-    }
-
-    void set_voicemail_info( AccountID account, pjsip_msg_body *body ){
-
-        int voicemail, pos_begin, pos_end;
-        std::string voice_str = "Voice-Message: ";
-        std::string delimiter = "/";
-        std::string msg_body, voicemail_str;
-
-        _debug("UserAgent: checking the voice message!\n");
-        // The voicemail message is formated like that:
-        // Voice-Message: 1/0  . 1 is the number we want to retrieve in this case
-
-        // We get the notification body
-        msg_body = (char*)body->data;
-
-        // We need the position of the first character of the string voice_str
-        pos_begin = msg_body.find(voice_str); 
-        // We need the position of the delimiter
-        pos_end = msg_body.find(delimiter); 
-
-        // So our voicemail number between the both index
-        try {
-
-            voicemail_str = msg_body.substr(pos_begin + voice_str.length(), pos_end - ( pos_begin + voice_str.length()));
-            std::cout << "voicemail number : " << voicemail_str << std::endl;
-            voicemail = atoi( voicemail_str.c_str() );
-        }
-        catch( std::out_of_range& e ){
-            std::cerr << e.what() << std::endl;
-        }
-
-        // We need now to notify the manager 
-        if( voicemail != 0 )
-            Manager::instance().startVoiceMessageNotification(account, voicemail);
-    }
-
-    void SIPVoIPLink::handle_reinvite (SIPCall *call) {
-
-        // Close the previous RTP session
-        _audiortp->closeRtpSession ();
-        call->setAudioStart (false);
-
-        // Create a new one with new info
-        if (_audiortp->createNewSession (call) >= 0) {
-            call->setAudioStart (true);
-        }
-    }
-
-
-    /*******************************/
-    /*   CALLBACKS IMPLEMENTATION  */
-    /*******************************/
-
-    void call_on_state_changed( pjsip_inv_session *inv, pjsip_event *e){
-
-        SIPCall *call;
-        AccountID accId;
-        SIPVoIPLink *link;
-        pjsip_rx_data *rdata;
-
-        /* Retrieve the call information */
-        call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]);
-        if(!call)
-            return;
-
-        //Retrieve the body message
-        rdata = e->body.tsx_state.src.rdata;
-
-        
-        /* If this is an outgoing INVITE that was created because of
-         * REFER/transfer, send NOTIFY to transferer.
-         */
-        if (call->getXferSub() && e->type==PJSIP_EVENT_TSX_STATE)  {
-            int st_code = -1;
-            pjsip_evsub_state ev_state = PJSIP_EVSUB_STATE_ACTIVE;
-
-            switch (call->getInvSession()->state) {
-                case PJSIP_INV_STATE_NULL:
-                case PJSIP_INV_STATE_CALLING:
-                    /* Do nothing */
-                    break;
-
-                case PJSIP_INV_STATE_EARLY:
-                case PJSIP_INV_STATE_CONNECTING:
-                    st_code = e->body.tsx_state.tsx->status_code;
-                    ev_state = PJSIP_EVSUB_STATE_ACTIVE;
-                    break;
-
-                case PJSIP_INV_STATE_CONFIRMED:
-                    /* When state is confirmed, send the final 200/OK and terminate
-                     * subscription.
-                     */
-                    st_code = e->body.tsx_state.tsx->status_code;
-                    ev_state = PJSIP_EVSUB_STATE_TERMINATED;
-                    break;
-
-                case PJSIP_INV_STATE_DISCONNECTED:
-                    st_code = e->body.tsx_state.tsx->status_code;
-                    ev_state = PJSIP_EVSUB_STATE_TERMINATED;
-                    break;
-
-                case PJSIP_INV_STATE_INCOMING:
-                    /* Nothing to do. Just to keep gcc from complaining about
-                     * unused enums.
-                     */
-                    break;
-            }
-
-            if (st_code != -1) {
-                pjsip_tx_data *tdata;
-                pj_status_t status;
-
-                status = pjsip_xfer_notify( call->getXferSub(),
-                        ev_state, st_code,
-                        NULL, &tdata);
-                if (status != PJ_SUCCESS) {
-                    _debug("UserAgent: Unable to create NOTIFY -- %d\n", status);
-                } else {
-                    status = pjsip_xfer_send_request(call->getXferSub(), tdata);
-                    if (status != PJ_SUCCESS) {
-                        _debug("UserAgent: Unable to send NOTIFY -- %d\n", status);
-                    }
-                }
-            }
-        }
-        else {
-
-            // The call is ringing - We need to handle this case only on outgoing call
-            if (inv->state == PJSIP_INV_STATE_EARLY && e->body.tsx_state.tsx->role == PJSIP_ROLE_UAC){
-                call->setConnectionState(Call::Ringing);
-                Manager::instance().peerRingingCall(call->getCallId());
-            }
-
-            // We receive a ACK - The connection is established
-            else if( inv->state == PJSIP_INV_STATE_CONFIRMED ){
-                    
-                /* If the call is a direct IP-to-IP call */
-                if (call->getCallConfiguration () == Call::IPtoIP) {
-                    link = SIPVoIPLink::instance("");
-                }
-                else {
-                    accId = Manager::instance().getAccountFromCall(call->getCallId());
-                    link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink(accId));
-                }
-                
-                if (link)
-                    link->SIPCallAnswered(call, rdata);
-            }
-
-            else if( inv->state == PJSIP_INV_STATE_DISCONNECTED ){
-                switch( inv->cause )
-                {
-                    /* The call terminates normally - BYE / CANCEL */
-                    case PJSIP_SC_OK:
-                    case PJSIP_SC_DECLINE:
-                    case PJSIP_SC_REQUEST_TERMINATED: 
-                        
-                        accId = Manager::instance().getAccountFromCall(call->getCallId());
-                        link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink(accId));
-                        if (link) {
-                            link->SIPCallClosed(call);
-                        }
-                        break; 
-
-                        /* The call connection failed */
-                    case PJSIP_SC_NOT_FOUND:            /* peer not found */
-                    case PJSIP_SC_REQUEST_TIMEOUT:      /* request timeout */
-                    case PJSIP_SC_NOT_ACCEPTABLE_HERE:  /* no compatible codecs */
-                    case PJSIP_SC_NOT_ACCEPTABLE_ANYWHERE:
-                    case PJSIP_SC_UNSUPPORTED_MEDIA_TYPE:
-                    case PJSIP_SC_UNAUTHORIZED:
-                        accId = Manager::instance().getAccountFromCall(call->getCallId());
-                        link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink(accId));
-                        if (link) {
-                            link->SIPCallServerFailure(call);
-                        }
-                        break;
-
-                    default:
-                        _debug ("sipvoiplink.cpp - line 1635 : Unhandled call state. This is probably a bug.\n");
-                        break;
-                }
-            }
-
-
-        }
-    }
-
-    void call_on_media_update( pjsip_inv_session *inv, pj_status_t status) {
-
-        const pjmedia_sdp_session *r_sdp;
-        SIPCall *call;
-
-        if (status != PJ_SUCCESS) {
-            _debug ("Error while negociating the offer\n");
-            return;
-        }
-
-        // Get the new sdp, result of the negociation
-        pjmedia_sdp_neg_get_active_local( inv->neg, &r_sdp );
-
-        call = reinterpret_cast<SIPCall *> (inv->mod_data[getModId()]);
-        // Clean the resulting sdp offer to create a new one (in case of a reinvite)
-        call->getLocalSDP()->clean_session_media();
-        // Set the fresh negociated one
-        call->getLocalSDP()->set_negociated_offer( r_sdp );
-    }
-
-    void call_on_forked(pjsip_inv_session *inv, pjsip_event *e){
-    }
-
-void call_on_tsx_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e){
-
-	if (tsx->role==PJSIP_ROLE_UAS && tsx->state==PJSIP_TSX_STATE_TRYING &&
-        	pjsip_method_cmp(&tsx->method, &pjsip_refer_method)==0)
-    	{
+}
+
+bool SIPVoIPLink::pjsip_shutdown ( void )
+{
+	if ( _endpt )
+	{
+		_debug ( "UserAgent: Shutting down...\n" );
+		busy_sleep ( 1000 );
+	}
+
+	pj_thread_join ( thread );
+	pj_thread_destroy ( thread );
+	thread = NULL;
+
+	/* Destroy endpoint. */
+	if ( _endpt )
+	{
+		pjsip_endpt_destroy ( _endpt );
+		_endpt = NULL;
+	}
+
+	/* Destroy pool and pool factory. */
+	if ( _pool )
+	{
+		pj_pool_release ( _pool );
+		_pool = NULL;
+		pj_caching_pool_destroy ( &_cp );
+	}
+
+	/* Shutdown PJLIB */
+	pj_shutdown();
+
+	/* Done. */
+}
+
+int getModId()
+{
+	return _mod_ua.id;
+}
+
+void set_voicemail_info ( AccountID account, pjsip_msg_body *body )
+{
+
+	int voicemail, pos_begin, pos_end;
+	std::string voice_str = "Voice-Message: ";
+	std::string delimiter = "/";
+	std::string msg_body, voicemail_str;
+
+	_debug ( "UserAgent: checking the voice message!\n" );
+	// The voicemail message is formated like that:
+	// Voice-Message: 1/0  . 1 is the number we want to retrieve in this case
+
+	// We get the notification body
+	msg_body = ( char* ) body->data;
+
+	// We need the position of the first character of the string voice_str
+	pos_begin = msg_body.find ( voice_str );
+	// We need the position of the delimiter
+	pos_end = msg_body.find ( delimiter );
+
+	// So our voicemail number between the both index
+	try
+	{
+
+		voicemail_str = msg_body.substr ( pos_begin + voice_str.length(), pos_end - ( pos_begin + voice_str.length() ) );
+		std::cout << "voicemail number : " << voicemail_str << std::endl;
+		voicemail = atoi ( voicemail_str.c_str() );
+	}
+	catch ( std::out_of_range& e )
+	{
+		std::cerr << e.what() << std::endl;
+	}
+
+	// We need now to notify the manager
+	if ( voicemail != 0 )
+		Manager::instance().startVoiceMessageNotification ( account, voicemail );
+}
+
+void SIPVoIPLink::handle_reinvite ( SIPCall *call )
+{
+
+	// Close the previous RTP session
+	_audiortp->closeRtpSession ();
+	call->setAudioStart ( false );
+
+	// Create a new one with new info
+	if ( _audiortp->createNewSession ( call ) >= 0 )
+	{
+		call->setAudioStart ( true );
+	}
+}
+
+
+/*******************************/
+/*   CALLBACKS IMPLEMENTATION  */
+/*******************************/
+
+void call_on_state_changed ( pjsip_inv_session *inv, pjsip_event *e )
+{
+
+	SIPCall *call;
+	AccountID accId;
+	SIPVoIPLink *link;
+	pjsip_rx_data *rdata;
+
+	/* Retrieve the call information */
+	call = reinterpret_cast<SIPCall*> ( inv->mod_data[_mod_ua.id] );
+	if ( !call )
+		return;
+
+	//Retrieve the body message
+	rdata = e->body.tsx_state.src.rdata;
+
+
+	/* If this is an outgoing INVITE that was created because of
+	 * REFER/transfer, send NOTIFY to transferer.
+	 */
+	if ( call->getXferSub() && e->type==PJSIP_EVENT_TSX_STATE )
+	{
+		int st_code = -1;
+		pjsip_evsub_state ev_state = PJSIP_EVSUB_STATE_ACTIVE;
+
+		switch ( call->getInvSession()->state )
+		{
+			case PJSIP_INV_STATE_NULL:
+			case PJSIP_INV_STATE_CALLING:
+				/* Do nothing */
+				break;
+
+			case PJSIP_INV_STATE_EARLY:
+			case PJSIP_INV_STATE_CONNECTING:
+				st_code = e->body.tsx_state.tsx->status_code;
+				ev_state = PJSIP_EVSUB_STATE_ACTIVE;
+				break;
+
+			case PJSIP_INV_STATE_CONFIRMED:
+				/* When state is confirmed, send the final 200/OK and terminate
+				 * subscription.
+				 */
+				st_code = e->body.tsx_state.tsx->status_code;
+				ev_state = PJSIP_EVSUB_STATE_TERMINATED;
+				break;
+
+			case PJSIP_INV_STATE_DISCONNECTED:
+				st_code = e->body.tsx_state.tsx->status_code;
+				ev_state = PJSIP_EVSUB_STATE_TERMINATED;
+				break;
+
+			case PJSIP_INV_STATE_INCOMING:
+				/* Nothing to do. Just to keep gcc from complaining about
+				 * unused enums.
+				 */
+				break;
+		}
+
+		if ( st_code != -1 )
+		{
+			pjsip_tx_data *tdata;
+			pj_status_t status;
+
+			status = pjsip_xfer_notify ( call->getXferSub(),
+			                             ev_state, st_code,
+			                             NULL, &tdata );
+			if ( status != PJ_SUCCESS )
+			{
+				_debug ( "UserAgent: Unable to create NOTIFY -- %d\n", status );
+			}
+			else
+			{
+				status = pjsip_xfer_send_request ( call->getXferSub(), tdata );
+				if ( status != PJ_SUCCESS )
+				{
+					_debug ( "UserAgent: Unable to send NOTIFY -- %d\n", status );
+				}
+			}
+		}
+	}
+	else
+	{
+
+		// The call is ringing - We need to handle this case only on outgoing call
+		if ( inv->state == PJSIP_INV_STATE_EARLY && e->body.tsx_state.tsx->role == PJSIP_ROLE_UAC )
+		{
+			call->setConnectionState ( Call::Ringing );
+			Manager::instance().peerRingingCall ( call->getCallId() );
+		}
+
+		// We receive a ACK - The connection is established
+		else if ( inv->state == PJSIP_INV_STATE_CONFIRMED )
+		{
+
+			/* If the call is a direct IP-to-IP call */
+			if ( call->getCallConfiguration () == Call::IPtoIP )
+			{
+				link = SIPVoIPLink::instance ( "" );
+			}
+			else
+			{
+				accId = Manager::instance().getAccountFromCall ( call->getCallId() );
+				link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) );
+			}
+
+			if ( link )
+				link->SIPCallAnswered ( call, rdata );
+		}
+
+		else if ( inv->state == PJSIP_INV_STATE_DISCONNECTED )
+		{
+			switch ( inv->cause )
+			{
+					/* The call terminates normally - BYE / CANCEL */
+				case PJSIP_SC_OK:
+				case PJSIP_SC_DECLINE:
+				case PJSIP_SC_REQUEST_TERMINATED:
+
+					accId = Manager::instance().getAccountFromCall ( call->getCallId() );
+					link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) );
+					if ( link )
+					{
+						link->SIPCallClosed ( call );
+					}
+					break;
+
+					/* The call connection failed */
+				case PJSIP_SC_NOT_FOUND:            /* peer not found */
+				case PJSIP_SC_REQUEST_TIMEOUT:      /* request timeout */
+				case PJSIP_SC_NOT_ACCEPTABLE_HERE:  /* no compatible codecs */
+				case PJSIP_SC_NOT_ACCEPTABLE_ANYWHERE:
+				case PJSIP_SC_UNSUPPORTED_MEDIA_TYPE:
+				case PJSIP_SC_UNAUTHORIZED:
+					accId = Manager::instance().getAccountFromCall ( call->getCallId() );
+					link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) );
+					if ( link )
+					{
+						link->SIPCallServerFailure ( call );
+					}
+					break;
+
+				default:
+					_debug ( "sipvoiplink.cpp - line 1635 : Unhandled call state. This is probably a bug.\n" );
+					break;
+			}
+		}
+
+
+	}
+}
+
+void call_on_media_update ( pjsip_inv_session *inv, pj_status_t status )
+{
+
+	const pjmedia_sdp_session *r_sdp;
+	SIPCall *call;
+
+	if ( status != PJ_SUCCESS )
+	{
+		_debug ( "Error while negociating the offer\n" );
+		return;
+	}
+
+	// Get the new sdp, result of the negociation
+	pjmedia_sdp_neg_get_active_local ( inv->neg, &r_sdp );
+
+	call = reinterpret_cast<SIPCall *> ( inv->mod_data[getModId() ] );
+	// Clean the resulting sdp offer to create a new one (in case of a reinvite)
+	call->getLocalSDP()->clean_session_media();
+	// Set the fresh negociated one
+	call->getLocalSDP()->set_negociated_offer ( r_sdp );
+}
+
+void call_on_forked ( pjsip_inv_session *inv, pjsip_event *e )
+{
+}
+
+void call_on_tsx_changed ( pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e )
+{
+
+	if ( tsx->role==PJSIP_ROLE_UAS && tsx->state==PJSIP_TSX_STATE_TRYING &&
+	        pjsip_method_cmp ( &tsx->method, &pjsip_refer_method ) ==0 )
+	{
 		/** Handle the refer method **/
-		onCallTransfered (inv, e->body.tsx_state.src.rdata);
-    	}
-    }
-
-    void regc_cb(struct pjsip_regc_cbparam *param){
-
-
-        //AccountID *id = static_cast<AccountID *> (param->token);
-        SIPAccount *account;
-
-        //_debug("UserAgent: Account ID is %s, Register result: %d, Status: %d\n", id->data(), param->status, param->code);
-        account = static_cast<SIPAccount *>(param->token);
-        if(!account)
-            return;
-
-        if (param->status == PJ_SUCCESS) {
-            if (param->code < 0 || param->code >= 300) {
-                /* Sometimes, the status is OK, but we still failed.
-                 * So checking the code for real result
-                 */
-                _debug("UserAgent: The error is: %d\n", param->code);
-                switch(param->code) {
-                    case 606:
-                        account->setRegistrationState(ErrorConfStun);
-                        break;
-                    case 503:
-                    case 408:
-                        account->setRegistrationState(ErrorHost);
-                        break;
-                    case 401:
-                    case 403:
-                    case 404:
-                        account->setRegistrationState(ErrorAuth);
-                        break;
-                    default:
-                        account->setRegistrationState(Error);
-                        break;
-                }
-                account->setRegister(false);
-            } else {
-                // Registration/Unregistration is success
-
-                if(account->isRegister())
-                    account->setRegistrationState(Registered);
-                else {
-                    account->setRegistrationState(Unregistered);
-                    account->setRegister(false);
-                }
-            }
-        } else {
-            account->setRegistrationState(ErrorAuth);
-            account->setRegister(false);
-        }
-
-    }
-
-    pj_bool_t 
-        mod_on_rx_request(pjsip_rx_data *rdata)
-        {
-
-            pj_status_t status;
-            pj_str_t reason;
-            unsigned options = 0;
-            pjsip_dialog* dialog;
-            pjsip_tx_data *tdata;
-            AccountID account_id;
-            pjsip_uri *uri;
-            pjsip_sip_uri *sip_uri;
-            std::string userName, server, caller, callerServer, peerNumber;
-            SIPVoIPLink *link;
-            CallID id;
-            SIPCall* call;
-            pjsip_inv_session *inv;
-            pjmedia_sdp_session *r_sdp;
-
-            // voicemail part
-            std::string method_name;
-            std::string request;
-
-            // Handle the incoming call invite in this function 
-            _debug("UserAgent: Callback on_rx_request is involved! *****************************************************\n");
-
-            /* First, let's got the username and server name from the invite.
-             * We will use them to detect which account is the callee.
-             */ 
-            uri = rdata->msg_info.to->uri;
-            sip_uri = (pjsip_sip_uri *) pjsip_uri_get_uri(uri);
-
-            userName = std::string(sip_uri->user.ptr, sip_uri->user.slen);
-            server = std::string(sip_uri->host.ptr, sip_uri->host.slen);
-
-            std::cout << userName << " ------------------ " << server << std::endl;
-
-            // Get the account id of callee from username and server
-            account_id = Manager::instance().getAccountIdFromNameAndServer(userName, server);
-
-            /* If we don't find any account to receive the call */
-            if(account_id == AccountNULL) {
-                _debug("UserAgent: Username %s doesn't match any account!\n",userName.c_str());
-                //return false;
-            }
-
-            /* Get the voip link associated to the incoming call */
-            /* The account must before have been associated to the call in ManagerImpl */
-            link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink(account_id));
-
-            /* If we can't find any voIP link to handle the incoming call */
-            if( link == 0 )
-            {
-                _debug("ERROR: can not retrieve the voiplink from the account ID...\n");
-                return false;
-            }
-
-            _debug("UserAgent: The receiver is : %s@%s\n", userName.data(), server.data());
-            _debug("UserAgent: The callee account id is %s\n", account_id.c_str());
-
-            /* Now, it is the time to find the information of the caller */
-            uri = rdata->msg_info.from->uri;
-            sip_uri = (pjsip_sip_uri *) pjsip_uri_get_uri(uri);
-
-
-            /* Retrieve only the fisrt characters */
-            caller = std::string(sip_uri->user.ptr, sip_uri->user.slen);
-            callerServer = std::string(sip_uri->host.ptr, sip_uri->host.slen);
-            peerNumber = caller + "@" + callerServer;
-
-            // Get the server voicemail notification
-            // Catch the NOTIFY message
-            if( rdata->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD )
-            {
-                method_name = "NOTIFY";  	
-                // Retrieve all the message. Should contains only the method name but ...
-                request =  rdata->msg_info.msg->line.req.method.name.ptr;
-                // Check if the message is a notification
-                if( request.find( method_name ) != (size_t)-1 ) {
-                    /* Notify the right account */
-                    set_voicemail_info( account_id, rdata->msg_info.msg->body );
-                    request.find( method_name );
-                }
-                pjsip_endpt_respond_stateless(_endpt, rdata, PJSIP_SC_OK, NULL, NULL, NULL);
-                return true;
-            }
-
-            // Handle an OPTIONS message
-            if (rdata->msg_info.msg->line.req.method.id == PJSIP_OPTIONS_METHOD) {
-                handle_incoming_options (rdata);
-                return true;
-            }
-
-            // Respond statelessly any non-INVITE requests with 500
-            if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) {
-                if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) {
-                    pj_strdup2(_pool, &reason, "user agent unable to handle this request ");
-                    pjsip_endpt_respond_stateless( _endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL,
-                            NULL);
-                    return true;
-                }
-            }
-
-            // Verify that we can handle the request
-            status = pjsip_inv_verify_request(rdata, &options, NULL, NULL, _endpt, NULL);
-            if (status != PJ_SUCCESS) {
-                pj_strdup2(_pool, &reason, "user agent unable to handle this INVITE ");
-                pjsip_endpt_respond_stateless( _endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL,
-                        NULL);
-                return true;
-            }
-
-            /******************************************* URL HOOK *********************************************/
-
-            if (Manager::instance().getConfigString (HOOKS, URLHOOK_SIP_ENABLED) == "1") {
-
-                std::string header_value;
-            
-                header_value = fetch_header_value (rdata->msg_info.msg, Manager::instance().getConfigString (HOOKS, URLHOOK_SIP_FIELD));
-            
-                if (header_value!=""){
-                    urlhook->addAction (header_value, 
-                                        Manager::instance().getConfigString (HOOKS, URLHOOK_COMMAND));
-                }
-            }
-
-            /************************************************************************************************/
-
-            // Generate a new call ID for the incoming call!
-            id = Manager::instance().getNewCallID();
-            call = new SIPCall(id, Call::Incoming, _pool);
-
-            /* If an error occured at the call creation */
-            if (!call) {
-                _debug("UserAgent: unable to create an incoming call");
-                return false;
-            }
-
-            // Have to do some stuff with the SDP
-            // Set the codec map, IP, peer number and so on... for the SIPCall object
-            setCallAudioLocal(call, link->getLocalIPAddress(), link->useStun(), link->getStunServer());
-            // We retrieve the remote sdp offer in the rdata struct to begin the negociation
-            call->getLocalSDP()->set_ip_address(link->getLocalIPAddress());
-            get_remote_sdp_from_offer( rdata, &r_sdp );
-            status = call->getLocalSDP()->receiving_initial_offer( r_sdp );
-	    if (status!=PJ_SUCCESS) {
-                delete call; call=0;
-                return false;
-	    }	 
-		
-
-            call->setConnectionState(Call::Progressing);
-            call->setPeerNumber(peerNumber);
-
-            call->initRecFileName();
-
-            // Notify UI there is an incoming call
-            if (Manager::instance().incomingCall(call, account_id)) {
-                // Add this call to the callAccountMap in ManagerImpl
-                Manager::instance().getAccountLink(account_id)->addCall(call);
-            } else {
-                // Fail to notify UI
-                delete call;
-                call = NULL;
-                _debug("UserAgent: Fail to notify UI!\n");
-                return false;
-            }
-
-
-            /* Create the local dialog (UAS) */
-            status = pjsip_dlg_create_uas(pjsip_ua_instance(), rdata, NULL, &dialog);
-            if (status != PJ_SUCCESS) {
-                pjsip_endpt_respond_stateless( _endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, &reason, NULL,
-                        NULL);
-                return true;
-            }
-
-            // Specify media capability during invite session creation
-            status = pjsip_inv_create_uas(dialog, rdata, call->getLocalSDP()->get_local_sdp_session(), 0, &inv);
-            PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
-
-            // Associate the call in the invite session
-            inv->mod_data[_mod_ua.id] = call;
-
-            // Send a 180/Ringing response
-            status = pjsip_inv_initial_answer(inv, rdata, PJSIP_SC_RINGING, NULL, NULL, &tdata);
-            PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
-            status = pjsip_inv_send_msg(inv, tdata);
-            PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
-
-            // Associate invite session to the current call
-            call->setInvSession(inv);
-
-            // Update the connection state
-            call->setConnectionState(Call::Ringing);
-
-            /* Done */
-            return true;
-
-        }
-
-    pj_bool_t mod_on_rx_response(pjsip_rx_data *rdata UNUSED) {
-        return PJ_SUCCESS;
-    }
-
-    void onCallTransfered(pjsip_inv_session *inv, pjsip_rx_data *rdata)
-    {
-
-        pj_status_t status;
-        pjsip_tx_data *tdata;
-        SIPCall *existing_call;
-        const pj_str_t str_refer_to = { (char*)"Refer-To", 8};
-        const pj_str_t str_refer_sub = { (char*)"Refer-Sub", 9 };
-        const pj_str_t str_ref_by = { (char*)"Referred-By", 11 };
-        pjsip_generic_string_hdr *refer_to;
-        pjsip_generic_string_hdr *refer_sub;
-        pjsip_hdr *ref_by_hdr;
-        pj_bool_t no_refer_sub = PJ_FALSE;
-        char *uri;
-        std::string tmp;
-        pjsip_status_code code;
-        pjsip_evsub *sub;
-
-        existing_call = (SIPCall *) inv->mod_data[_mod_ua.id];
-
-        /* Find the Refer-To header */
-        refer_to = (pjsip_generic_string_hdr*)
-            pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_to, NULL);
-
-        if (refer_to == NULL) {
-            /* Invalid Request.
-             * No Refer-To header!
-             */
-            _debug("UserAgent: Received REFER without Refer-To header!\n");
-            pjsip_dlg_respond( inv->dlg, rdata, 400, NULL, NULL, NULL);
-            return;
-        }
-
-        /* Find optional Refer-Sub header */
-        refer_sub = (pjsip_generic_string_hdr*)
-            pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_sub, NULL);
-
-        if (refer_sub) {
-            if (!pj_strnicmp2(&refer_sub->hvalue, "true", 4)==0)
-                no_refer_sub = PJ_TRUE;
-        }
-
-        /* Find optional Referred-By header (to be copied onto outgoing INVITE
-         * request.
-         */
-        ref_by_hdr = (pjsip_hdr*)
-            pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_ref_by,
-                    NULL);
-
-        /* Notify callback */
-        code = PJSIP_SC_ACCEPTED;
-
-        _debug("UserAgent: Call to %.*s is being transfered to %.*s\n",
-                (int)inv->dlg->remote.info_str.slen,
-                inv->dlg->remote.info_str.ptr,
-                (int)refer_to->hvalue.slen,
-                refer_to->hvalue.ptr);
-
-        if (no_refer_sub) {
-            /*
-             * Always answer with 2xx.
-             */
-            pjsip_tx_data *tdata;
-            const pj_str_t str_false = { (char*)"false", 5};
-            pjsip_hdr *hdr;
-
-            status = pjsip_dlg_create_response(inv->dlg, rdata, code, NULL,
-                    &tdata);
-            if (status != PJ_SUCCESS) {
-                _debug("UserAgent: Unable to create 2xx response to REFER -- %d\n", status);
-                return;
-            }
-
-            /* Add Refer-Sub header */
-            hdr = (pjsip_hdr*)
-                pjsip_generic_string_hdr_create(tdata->pool, &str_refer_sub,
-                        &str_false);
-            pjsip_msg_add_hdr(tdata->msg, hdr);
-
-
-            /* Send answer */
-            status = pjsip_dlg_send_response(inv->dlg, pjsip_rdata_get_tsx(rdata),
-                    tdata);
-            if (status != PJ_SUCCESS) {
-                _debug("UserAgent: Unable to create 2xx response to REFER -- %d\n", status);
-                return;
-            }
-
-            /* Don't have subscription */
-            sub = NULL;
-
-        } else {
-            struct pjsip_evsub_user xfer_cb;
-            pjsip_hdr hdr_list;
-
-            /* Init callback */
-            pj_bzero(&xfer_cb, sizeof(xfer_cb));
-            xfer_cb.on_evsub_state = &xfer_svr_cb;
-
-            /* Init addiTHIS_FILE, THIS_FILE, tional header list to be sent with REFER response */
-            pj_list_init(&hdr_list);
-
-            /* Create transferee event subscription */
-            status = pjsip_xfer_create_uas( inv->dlg, &xfer_cb, rdata, &sub);
-            if (status != PJ_SUCCESS) {
-                _debug("UserAgent: Unable to create xfer uas -- %d\n", status);
-                pjsip_dlg_respond( inv->dlg, rdata, 500, NULL, NULL, NULL);
-                return;
-            }
-
-            /* If there's Refer-Sub header and the value is "true", send back
-             * Refer-Sub in the response with value "true" too.
-             */
-            if (refer_sub) {
-                const pj_str_t str_true = { (char*)"true", 4 };
-                pjsip_hdr *hdr;
-
-                hdr = (pjsip_hdr*)
-                    pjsip_generic_string_hdr_create(inv->dlg->pool,
-                            &str_refer_sub,
-                            &str_true);
-                pj_list_push_back(&hdr_list, hdr);
-
-            }
-
-            /* Accept the REFER request, send 2xx. */
-            pjsip_xfer_accept(sub, rdata, code, &hdr_list);
-
-            /* Create initial NOTIFY request */
-            status = pjsip_xfer_notify( sub, PJSIP_EVSUB_STATE_ACTIVE,
-                    100, NULL, &tdata);
-            if (status != PJ_SUCCESS) {
-                _debug("UserAgent: Unable to create NOTIFY to REFER -- %d", status);
-                return;
-            }
-
-            /* Send initial NOTIFY request */
-            status = pjsip_xfer_send_request( sub, tdata);
-            if (status != PJ_SUCCESS) {
-                _debug("UserAgent: Unable to send NOTIFY to REFER -- %d\n", status);
-                return;
-            }
-        }
-
-        /* We're cheating here.
-         * We need to get a null terminated string from a pj_str_t.
-         * So grab the pointer from the hvalue and NULL terminate it, knowing
-         * that the NULL position will be occupied by a newline. 
-         */
-        uri = refer_to->hvalue.ptr;
-        uri[refer_to->hvalue.slen] = '\0';
-
-        /* Now make the outgoing call. */
-        tmp = std::string(uri);
-
-        if(existing_call == NULL) {
-            _debug("UserAgent: Call doesn't exist!\n");
-            return;
-        }
-
-        AccountID accId = Manager::instance().getAccountFromCall(existing_call->getCallId());
-        CallID newCallId = Manager::instance().getNewCallID();
-
-        if(!Manager::instance().outgoingCall(accId, newCallId, tmp)) {
-
-            /* Notify xferer about the error (if we have subscription) */
-            if (sub) {
-                status = pjsip_xfer_notify(sub, PJSIP_EVSUB_STATE_TERMINATED,
-                        500, NULL, &tdata);
-                if (status != PJ_SUCCESS) {
-                    _debug("UserAgent: Unable to create NOTIFY to REFER -- %d\n", status);
-                    return;
-                }
-                status = pjsip_xfer_send_request(sub, tdata);
-                if (status != PJ_SUCCESS) {
-                    _debug("UserAgent: Unable to send NOTIFY to REFER -- %d\n", status);
-                    return;
-                }
-            }
-            return;
-        }
-
-        SIPCall* newCall;
-        SIPVoIPLink *link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink(accId));
-        if(link) {
-            newCall = dynamic_cast<SIPCall *>(link->getCall(newCallId));
-            if(!newCall) {
-                _debug("UserAgent: can not find the call from sipvoiplink!\n");
-                return;
-            }
-        }
-
-        if (sub) {
-            /* Put the server subscription in inv_data.
-             * Subsequent state changed in pjsua_inv_on_state_changed() will be
-             * reported back to the server subscription.
-             */
-            newCall->setXferSub(sub);
-
-            /* Put the invite_data in the subscription. */
-            pjsip_evsub_set_mod_data(sub, _mod_ua.id,
-                    newCall);
-        }    
-    }
-
-
-
-    void xfer_func_cb( pjsip_evsub *sub, pjsip_event *event){
-        
-
-        PJ_UNUSED_ARG(event);
-       
-        // _debug(" %s \n", event->body.rx_msg.rdata->msg_info.msg_buf);
-            
-
-        
-        // _debug("UserAgent: pjsip_evsub_get_state_name: %s \n", pjsip_evsub_get_state_name(sub));
-
-        /*
-         * When subscription is accepted (got 200/OK to REFER), check if 
-         * subscription suppressed.
-         */
-        if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_ACCEPTED) {
-             
-            _debug("Transfer accepted! Waiting for notifications. \n");
-
-            /*
-            pjsip_rx_data *rdata;
-            pjsip_generic_string_hdr *refer_sub;
-            const pj_str_t REFER_SUB = {(char*)"Refer-Sub", 9 };
-
-            SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *> (pjsip_evsub_get_mod_data(sub, _mod_ua.id));
-            
-            // Must be receipt of response message 
-            pj_assert(event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
-            rdata = event->body.tsx_state.src.rdata;
- 
-            // Find Refer-Sub header 
-            refer_sub = (pjsip_generic_string_hdr*)pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &REFER_SUB, NULL);
-                
-            // Check if subscription is suppressed 
-            if (refer_sub && pj_stricmp2(&refer_sub->hvalue, "false")==0) {
-                // Since no subscription is desired, assume that call has been transfered successfully.
-                    
-                if (link) {
-                    // It's the time to stop the RTP
-                      
-                    link->transferStep2();
-                }
-                    
-                // Yes, subscription is suppressed.Terminate our subscription now.
-                _debug("UserAgent: Xfer subscription suppressed, terminating event subcription...\n");
-                pjsip_evsub_terminate(sub, PJ_TRUE);
-            } 
-                
-            
-            else {
-              // Notify application about call transfer progress. Initially notify with 100/Accepted status.
-                 
-                _debug("UserAgent: Xfer subscription 100/Accepted received...\n");
-            }
-            */
-        }
-        /*
-         * On incoming NOTIFY, notify application about call transfer progress.
-         */
-        else if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_ACTIVE ||
-                   pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED)
-        {
-            pjsip_msg *msg;
-            pjsip_msg_body *body;
-            pjsip_status_line status_line;
-            pj_bool_t is_last;
-            pj_bool_t cont;
-            pj_status_t status;
-
-            std::string noresource;
-            std::string ringing;
-            std::string request;
-
-            noresource = "noresource";
-            ringing = "Ringing";
-
-
-            SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *> (pjsip_evsub_get_mod_data(sub, _mod_ua.id));
-
-            /* When subscription is terminated, clear the xfer_sub member of 
-             * the inv_data.
-             */
-            
-            if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) {
-                pjsip_evsub_set_mod_data(sub, _mod_ua.id, NULL);
-                _debug("UserAgent: Xfer client subscription terminated\n");
-
-            }
-            
-            if (!link || !event) {
-                /* Application is not interested with call progress status */
-                _debug("UserAgent: Either link or event is empty!\n");
-                return;
-            }
-            
-            
-
-            /* This better be a NOTIFY request */
-            if (event->type == PJSIP_EVENT_TSX_STATE &&
-                    event->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
-            {
-                
-                pjsip_rx_data *rdata;
-
-                rdata = event->body.tsx_state.src.rdata;
-
-            
-                /* Check if there's body */
-                msg = rdata->msg_info.msg;
-                body = msg->body;
-                if (!body) {
-                  // if (call->getCallConfiguration () == Call::IPtoIP) {
-                  //   _debug("UserAgent: IptoIp NOTIFY without message body\n");
-                  // }
-                  // else{
-                      _debug("UserAgent: Warning! Received NOTIFY without message body\n");
-                      return;
-                      // }
-                }
-
-                
-
-                /* Check for appropriate content */
-                if (pj_stricmp2(&body->content_type.type, "message") != 0 ||
-                        pj_stricmp2(&body->content_type.subtype, "sipfrag") != 0)
-                {
-                    _debug("UserAgent: Warning! Received NOTIFY with non message/sipfrag content\n");
-                    return;
-                }
-
-                /* Try to parse the content */
-                status = pjsip_parse_status_line((char*)body->data, body->len,
-                        &status_line);
-                if (status != PJ_SUCCESS) {
-                    _debug("UserAgent: Warning! Received NOTIFY with invalid message/sipfrag content\n");
-                    return;
-                }
-
-            } else {
-                _debug("UserAgent: Set code to 500!\n");
-                status_line.code = 500;
-                status_line.reason = *pjsip_get_status_text(500);
-            }
-            
-            
-            if(event->body.rx_msg.rdata->msg_info.msg_buf != NULL) {
-                request = event->body.rx_msg.rdata->msg_info.msg_buf;
-                if (request.find( noresource ) != -1) {
-                    _debug("UserAgent: NORESOURCE for transfer!\n");
-                    link->transferStep2();
-                    pjsip_evsub_terminate(sub, PJ_TRUE);
-                    return;
-                }
-
-                if (request.find( ringing ) != -1){
-                    _debug("UserAgent: transfered call RINGING!\n");
-                    link->transferStep2();
-                    pjsip_evsub_terminate(sub, PJ_TRUE);
-                    return;
-                }
-            }
-
-            
-            // Get current call
-            SIPCall *call = dynamic_cast<SIPCall *>(link->getCall(Manager::instance().getCurrentCallId()));
-            if(!call) {
-                _debug("UserAgent: Call doesn't exit!\n");
-                return;
-            }
-
-
-            /* Notify application */
-            is_last = (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED);
-            cont = !is_last;
-
-            if(status_line.code/100 == 2) {
-                
-                _debug("UserAgent: Try to stop rtp!\n");
-                pjsip_tx_data *tdata;
-
-                status = pjsip_inv_end_session(call->getInvSession(), PJSIP_SC_GONE, NULL, &tdata);
-                if(status != PJ_SUCCESS) {
-                    _debug("UserAgent: Fail to create end session msg!\n");
-                } else {
-                    status = pjsip_inv_send_msg(call->getInvSession(), tdata);
-                    if(status != PJ_SUCCESS) 
-                        _debug("UserAgent: Fail to send end session msg!\n");
-                }
-
-                link->transferStep2();
-                cont = PJ_FALSE;
-            }
-
-            if (!cont) {
-                pjsip_evsub_set_mod_data(sub, _mod_ua.id, NULL);
-            }
-
-        }
-
-    }
-
-
-    void xfer_svr_cb(pjsip_evsub *sub, pjsip_event *event)
-    {
-        
-        PJ_UNUSED_ARG(event);
-
-        /*
-         * When subscription is terminated, clear the xfer_sub member of 
-         * the inv_data.
-         */
-        if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) {
-            SIPCall *call;
-
-            call = (SIPCall*) pjsip_evsub_get_mod_data(sub, _mod_ua.id);
-            if (!call)
-                return;
-
-            pjsip_evsub_set_mod_data(sub, _mod_ua.id, NULL);
-            call->setXferSub(NULL);
-
-            _debug("UserAgent: Xfer server subscription terminated\n");
-        }    
-    }
-
-    void on_rx_offer( pjsip_inv_session *inv, const pjmedia_sdp_session *offer ){
+		onCallTransfered ( inv, e->body.tsx_state.src.rdata );
+	}
+}
+
+void regc_cb ( struct pjsip_regc_cbparam *param )
+{
+
+
+	//AccountID *id = static_cast<AccountID *> (param->token);
+	SIPAccount *account;
+
+	//_debug("UserAgent: Account ID is %s, Register result: %d, Status: %d\n", id->data(), param->status, param->code);
+	account = static_cast<SIPAccount *> ( param->token );
+	if ( !account )
+		return;
+
+	if ( param->status == PJ_SUCCESS )
+	{
+		if ( param->code < 0 || param->code >= 300 )
+		{
+			/* Sometimes, the status is OK, but we still failed.
+			 * So checking the code for real result
+			 */
+			_debug ( "UserAgent: The error is: %d\n", param->code );
+			switch ( param->code )
+			{
+				case 606:
+					account->setRegistrationState ( ErrorConfStun );
+					break;
+				case 503:
+				case 408:
+					account->setRegistrationState ( ErrorHost );
+					break;
+				case 401:
+				case 403:
+				case 404:
+					account->setRegistrationState ( ErrorAuth );
+					break;
+				default:
+					account->setRegistrationState ( Error );
+					break;
+			}
+			account->setRegister ( false );
+		}
+		else
+		{
+			// Registration/Unregistration is success
+
+			if ( account->isRegister() )
+				account->setRegistrationState ( Registered );
+			else
+			{
+				account->setRegistrationState ( Unregistered );
+				account->setRegister ( false );
+			}
+		}
+	}
+	else
+	{
+		account->setRegistrationState ( ErrorAuth );
+		account->setRegister ( false );
+	}
+
+}
+
+pj_bool_t
+mod_on_rx_request ( pjsip_rx_data *rdata )
+{
+
+	pj_status_t status;
+	pj_str_t reason;
+	unsigned options = 0;
+	pjsip_dialog* dialog;
+	pjsip_tx_data *tdata;
+	AccountID account_id;
+	pjsip_uri *uri;
+	pjsip_sip_uri *sip_uri;
+	std::string userName, server, caller, callerServer, peerNumber;
+	SIPVoIPLink *link;
+	CallID id;
+	SIPCall* call;
+	pjsip_inv_session *inv;
+	pjmedia_sdp_session *r_sdp;
+
+	// voicemail part
+	std::string method_name;
+	std::string request;
+
+	// Handle the incoming call invite in this function
+	_debug ( "UserAgent: Callback on_rx_request is involved! *****************************************************\n" );
+
+	/* First, let's got the username and server name from the invite.
+	 * We will use them to detect which account is the callee.
+	 */
+	uri = rdata->msg_info.to->uri;
+	sip_uri = ( pjsip_sip_uri * ) pjsip_uri_get_uri ( uri );
+
+	userName = std::string ( sip_uri->user.ptr, sip_uri->user.slen );
+	server = std::string ( sip_uri->host.ptr, sip_uri->host.slen );
+
+	std::cout << userName << " ------------------ " << server << std::endl;
+
+	// Get the account id of callee from username and server
+	account_id = Manager::instance().getAccountIdFromNameAndServer ( userName, server );
+
+	/* If we don't find any account to receive the call */
+	if ( account_id == AccountNULL )
+	{
+		_debug ( "UserAgent: Username %s doesn't match any account!\n",userName.c_str() );
+		//return false;
+	}
+
+	/* Get the voip link associated to the incoming call */
+	/* The account must before have been associated to the call in ManagerImpl */
+	link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( account_id ) );
+
+	/* If we can't find any voIP link to handle the incoming call */
+	if ( link == 0 )
+	{
+		_debug ( "ERROR: can not retrieve the voiplink from the account ID...\n" );
+		return false;
+	}
+
+	_debug ( "UserAgent: The receiver is : %s@%s\n", userName.data(), server.data() );
+	_debug ( "UserAgent: The callee account id is %s\n", account_id.c_str() );
+
+	/* Now, it is the time to find the information of the caller */
+	uri = rdata->msg_info.from->uri;
+	sip_uri = ( pjsip_sip_uri * ) pjsip_uri_get_uri ( uri );
+
+
+	/* Retrieve only the fisrt characters */
+	caller = std::string ( sip_uri->user.ptr, sip_uri->user.slen );
+	callerServer = std::string ( sip_uri->host.ptr, sip_uri->host.slen );
+	peerNumber = caller + "@" + callerServer;
+
+	// Get the server voicemail notification
+	// Catch the NOTIFY message
+	if ( rdata->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD )
+	{
+		method_name = "NOTIFY";
+		// Retrieve all the message. Should contains only the method name but ...
+		request =  rdata->msg_info.msg->line.req.method.name.ptr;
+		// Check if the message is a notification
+		if ( request.find ( method_name ) != ( size_t )-1 )
+		{
+			/* Notify the right account */
+			set_voicemail_info ( account_id, rdata->msg_info.msg->body );
+			request.find ( method_name );
+		}
+		pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_OK, NULL, NULL, NULL );
+		return true;
+	}
+
+	// Handle an OPTIONS message
+	if ( rdata->msg_info.msg->line.req.method.id == PJSIP_OPTIONS_METHOD )
+	{
+		handle_incoming_options ( rdata );
+		return true;
+	}
+
+	// Respond statelessly any non-INVITE requests with 500
+	if ( rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD )
+	{
+		if ( rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD )
+		{
+			pj_strdup2 ( _pool, &reason, "user agent unable to handle this request " );
+			pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL,
+			                                NULL );
+			return true;
+		}
+	}
+
+	// Verify that we can handle the request
+	status = pjsip_inv_verify_request ( rdata, &options, NULL, NULL, _endpt, NULL );
+	if ( status != PJ_SUCCESS )
+	{
+		pj_strdup2 ( _pool, &reason, "user agent unable to handle this INVITE " );
+		pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL,
+		                                NULL );
+		return true;
+	}
+
+	/******************************************* URL HOOK *********************************************/
+
+	if ( Manager::instance().getConfigString ( HOOKS, URLHOOK_SIP_ENABLED ) == "1" )
+	{
+
+		std::string header_value;
+
+		header_value = fetch_header_value ( rdata->msg_info.msg, Manager::instance().getConfigString ( HOOKS, URLHOOK_SIP_FIELD ) );
+
+		if ( header_value!="" )
+		{
+			urlhook->addAction ( header_value,
+			                     Manager::instance().getConfigString ( HOOKS, URLHOOK_COMMAND ) );
+		}
+	}
+
+	/************************************************************************************************/
+
+	// Generate a new call ID for the incoming call!
+	id = Manager::instance().getNewCallID();
+	call = new SIPCall ( id, Call::Incoming, _pool );
+
+	/* If an error occured at the call creation */
+	if ( !call )
+	{
+		_debug ( "UserAgent: unable to create an incoming call" );
+		return false;
+	}
+
+	// Have to do some stuff with the SDP
+	// Set the codec map, IP, peer number and so on... for the SIPCall object
+	setCallAudioLocal ( call, link->getLocalIPAddress(), link->useStun(), link->getStunServer() );
+	// We retrieve the remote sdp offer in the rdata struct to begin the negociation
+	call->getLocalSDP()->set_ip_address ( link->getLocalIPAddress() );
+	get_remote_sdp_from_offer ( rdata, &r_sdp );
+// 	_debug("r_sdp = %s\n", r_sdp);
+	status = call->getLocalSDP()->receiving_initial_offer ( r_sdp );
+	if ( status!=PJ_SUCCESS )
+	{
+		delete call; call=0;
+		return false;
+	}
+
+
+	call->setConnectionState ( Call::Progressing );
+	call->setPeerNumber ( peerNumber );
+
+	call->initRecFileName();
+
+	// Notify UI there is an incoming call
+	if ( Manager::instance().incomingCall ( call, account_id ) )
+	{
+		// Add this call to the callAccountMap in ManagerImpl
+		Manager::instance().getAccountLink ( account_id )->addCall ( call );
+	}
+	else
+	{
+		// Fail to notify UI
+		delete call;
+		call = NULL;
+		_debug ( "UserAgent: Fail to notify UI!\n" );
+		return false;
+	}
+
+
+	/* Create the local dialog (UAS) */
+	status = pjsip_dlg_create_uas ( pjsip_ua_instance(), rdata, NULL, &dialog );
+	if ( status != PJ_SUCCESS )
+	{
+		pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, &reason, NULL,
+		                                NULL );
+		return true;
+	}
+
+	// Specify media capability during invite session creation
+	status = pjsip_inv_create_uas ( dialog, rdata, call->getLocalSDP()->get_local_sdp_session(), 0, &inv );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Associate the call in the invite session
+	inv->mod_data[_mod_ua.id] = call;
+
+	// Send a 180/Ringing response
+	status = pjsip_inv_initial_answer ( inv, rdata, PJSIP_SC_RINGING, NULL, NULL, &tdata );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+	status = pjsip_inv_send_msg ( inv, tdata );
+	PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 );
+
+	// Associate invite session to the current call
+	call->setInvSession ( inv );
+
+	// Update the connection state
+	call->setConnectionState ( Call::Ringing );
+
+	/* Done */
+	return true;
+
+}
+
+pj_bool_t mod_on_rx_response ( pjsip_rx_data *rdata UNUSED )
+{
+	return PJ_SUCCESS;
+}
+
+void onCallTransfered ( pjsip_inv_session *inv, pjsip_rx_data *rdata )
+{
+
+	pj_status_t status;
+	pjsip_tx_data *tdata;
+	SIPCall *existing_call;
+	const pj_str_t str_refer_to = { ( char* ) "Refer-To", 8};
+	const pj_str_t str_refer_sub = { ( char* ) "Refer-Sub", 9 };
+	const pj_str_t str_ref_by = { ( char* ) "Referred-By", 11 };
+	pjsip_generic_string_hdr *refer_to;
+	pjsip_generic_string_hdr *refer_sub;
+	pjsip_hdr *ref_by_hdr;
+	pj_bool_t no_refer_sub = PJ_FALSE;
+	char *uri;
+	std::string tmp;
+	pjsip_status_code code;
+	pjsip_evsub *sub;
+
+	existing_call = ( SIPCall * ) inv->mod_data[_mod_ua.id];
+
+	/* Find the Refer-To header */
+	refer_to = ( pjsip_generic_string_hdr* )
+	           pjsip_msg_find_hdr_by_name ( rdata->msg_info.msg, &str_refer_to, NULL );
+
+	if ( refer_to == NULL )
+	{
+		/* Invalid Request.
+		 * No Refer-To header!
+		 */
+		_debug ( "UserAgent: Received REFER without Refer-To header!\n" );
+		pjsip_dlg_respond ( inv->dlg, rdata, 400, NULL, NULL, NULL );
+		return;
+	}
+
+	/* Find optional Refer-Sub header */
+	refer_sub = ( pjsip_generic_string_hdr* )
+	            pjsip_msg_find_hdr_by_name ( rdata->msg_info.msg, &str_refer_sub, NULL );
+
+	if ( refer_sub )
+	{
+		if ( !pj_strnicmp2 ( &refer_sub->hvalue, "true", 4 ) ==0 )
+			no_refer_sub = PJ_TRUE;
+	}
+
+	/* Find optional Referred-By header (to be copied onto outgoing INVITE
+	 * request.
+	 */
+	ref_by_hdr = ( pjsip_hdr* )
+	             pjsip_msg_find_hdr_by_name ( rdata->msg_info.msg, &str_ref_by,
+	                                          NULL );
+
+	/* Notify callback */
+	code = PJSIP_SC_ACCEPTED;
+
+	_debug ( "UserAgent: Call to %.*s is being transfered to %.*s\n",
+	         ( int ) inv->dlg->remote.info_str.slen,
+	         inv->dlg->remote.info_str.ptr,
+	         ( int ) refer_to->hvalue.slen,
+	         refer_to->hvalue.ptr );
+
+	if ( no_refer_sub )
+	{
+		/*
+		 * Always answer with 2xx.
+		 */
+		pjsip_tx_data *tdata;
+		const pj_str_t str_false = { ( char* ) "false", 5};
+		pjsip_hdr *hdr;
+
+		status = pjsip_dlg_create_response ( inv->dlg, rdata, code, NULL,
+		                                     &tdata );
+		if ( status != PJ_SUCCESS )
+		{
+			_debug ( "UserAgent: Unable to create 2xx response to REFER -- %d\n", status );
+			return;
+		}
+
+		/* Add Refer-Sub header */
+		hdr = ( pjsip_hdr* )
+		      pjsip_generic_string_hdr_create ( tdata->pool, &str_refer_sub,
+		                                        &str_false );
+		pjsip_msg_add_hdr ( tdata->msg, hdr );
+
+
+		/* Send answer */
+		status = pjsip_dlg_send_response ( inv->dlg, pjsip_rdata_get_tsx ( rdata ),
+		                                   tdata );
+		if ( status != PJ_SUCCESS )
+		{
+			_debug ( "UserAgent: Unable to create 2xx response to REFER -- %d\n", status );
+			return;
+		}
+
+		/* Don't have subscription */
+		sub = NULL;
+
+	}
+	else
+	{
+		struct pjsip_evsub_user xfer_cb;
+		pjsip_hdr hdr_list;
+
+		/* Init callback */
+		pj_bzero ( &xfer_cb, sizeof ( xfer_cb ) );
+		xfer_cb.on_evsub_state = &xfer_svr_cb;
+
+		/* Init addiTHIS_FILE, THIS_FILE, tional header list to be sent with REFER response */
+		pj_list_init ( &hdr_list );
+
+		/* Create transferee event subscription */
+		status = pjsip_xfer_create_uas ( inv->dlg, &xfer_cb, rdata, &sub );
+		if ( status != PJ_SUCCESS )
+		{
+			_debug ( "UserAgent: Unable to create xfer uas -- %d\n", status );
+			pjsip_dlg_respond ( inv->dlg, rdata, 500, NULL, NULL, NULL );
+			return;
+		}
+
+		/* If there's Refer-Sub header and the value is "true", send back
+		 * Refer-Sub in the response with value "true" too.
+		 */
+		if ( refer_sub )
+		{
+			const pj_str_t str_true = { ( char* ) "true", 4 };
+			pjsip_hdr *hdr;
+
+			hdr = ( pjsip_hdr* )
+			      pjsip_generic_string_hdr_create ( inv->dlg->pool,
+			                                        &str_refer_sub,
+			                                        &str_true );
+			pj_list_push_back ( &hdr_list, hdr );
+
+		}
+
+		/* Accept the REFER request, send 2xx. */
+		pjsip_xfer_accept ( sub, rdata, code, &hdr_list );
+
+		/* Create initial NOTIFY request */
+		status = pjsip_xfer_notify ( sub, PJSIP_EVSUB_STATE_ACTIVE,
+		                             100, NULL, &tdata );
+		if ( status != PJ_SUCCESS )
+		{
+			_debug ( "UserAgent: Unable to create NOTIFY to REFER -- %d", status );
+			return;
+		}
+
+		/* Send initial NOTIFY request */
+		status = pjsip_xfer_send_request ( sub, tdata );
+		if ( status != PJ_SUCCESS )
+		{
+			_debug ( "UserAgent: Unable to send NOTIFY to REFER -- %d\n", status );
+			return;
+		}
+	}
+
+	/* We're cheating here.
+	 * We need to get a null terminated string from a pj_str_t.
+	 * So grab the pointer from the hvalue and NULL terminate it, knowing
+	 * that the NULL position will be occupied by a newline.
+	 */
+	uri = refer_to->hvalue.ptr;
+	uri[refer_to->hvalue.slen] = '\0';
+
+	/* Now make the outgoing call. */
+	tmp = std::string ( uri );
+
+	if ( existing_call == NULL )
+	{
+		_debug ( "UserAgent: Call doesn't exist!\n" );
+		return;
+	}
+
+	AccountID accId = Manager::instance().getAccountFromCall ( existing_call->getCallId() );
+	CallID newCallId = Manager::instance().getNewCallID();
+
+	if ( !Manager::instance().outgoingCall ( accId, newCallId, tmp ) )
+	{
+
+		/* Notify xferer about the error (if we have subscription) */
+		if ( sub )
+		{
+			status = pjsip_xfer_notify ( sub, PJSIP_EVSUB_STATE_TERMINATED,
+			                             500, NULL, &tdata );
+			if ( status != PJ_SUCCESS )
+			{
+				_debug ( "UserAgent: Unable to create NOTIFY to REFER -- %d\n", status );
+				return;
+			}
+			status = pjsip_xfer_send_request ( sub, tdata );
+			if ( status != PJ_SUCCESS )
+			{
+				_debug ( "UserAgent: Unable to send NOTIFY to REFER -- %d\n", status );
+				return;
+			}
+		}
+		return;
+	}
+
+	SIPCall* newCall;
+	SIPVoIPLink *link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) );
+	if ( link )
+	{
+		newCall = dynamic_cast<SIPCall *> ( link->getCall ( newCallId ) );
+		if ( !newCall )
+		{
+			_debug ( "UserAgent: can not find the call from sipvoiplink!\n" );
+			return;
+		}
+	}
+
+	if ( sub )
+	{
+		/* Put the server subscription in inv_data.
+		 * Subsequent state changed in pjsua_inv_on_state_changed() will be
+		 * reported back to the server subscription.
+		 */
+		newCall->setXferSub ( sub );
+
+		/* Put the invite_data in the subscription. */
+		pjsip_evsub_set_mod_data ( sub, _mod_ua.id,
+		                           newCall );
+	}
+}
+
+
+
+void xfer_func_cb ( pjsip_evsub *sub, pjsip_event *event )
+{
+
+
+	PJ_UNUSED_ARG ( event );
+
+	// _debug(" %s \n", event->body.rx_msg.rdata->msg_info.msg_buf);
+
+
+
+	// _debug("UserAgent: pjsip_evsub_get_state_name: %s \n", pjsip_evsub_get_state_name(sub));
+
+	/*
+	 * When subscription is accepted (got 200/OK to REFER), check if
+	 * subscription suppressed.
+	 */
+	if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_ACCEPTED )
+	{
+
+		_debug ( "Transfer accepted! Waiting for notifications. \n" );
+
+		/*
+		pjsip_rx_data *rdata;
+		pjsip_generic_string_hdr *refer_sub;
+		const pj_str_t REFER_SUB = {(char*)"Refer-Sub", 9 };
+
+		SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *> (pjsip_evsub_get_mod_data(sub, _mod_ua.id));
+
+		// Must be receipt of response message
+		pj_assert(event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
+		rdata = event->body.tsx_state.src.rdata;
+
+		// Find Refer-Sub header
+		refer_sub = (pjsip_generic_string_hdr*)pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &REFER_SUB, NULL);
+		    
+		// Check if subscription is suppressed
+		if (refer_sub && pj_stricmp2(&refer_sub->hvalue, "false")==0) {
+		    // Since no subscription is desired, assume that call has been transfered successfully.
+		        
+		    if (link) {
+		        // It's the time to stop the RTP
+		          
+		        link->transferStep2();
+		    }
+		        
+		    // Yes, subscription is suppressed.Terminate our subscription now.
+		    _debug("UserAgent: Xfer subscription suppressed, terminating event subcription...\n");
+		    pjsip_evsub_terminate(sub, PJ_TRUE);
+		}
+		    
+
+		else {
+		  // Notify application about call transfer progress. Initially notify with 100/Accepted status.
+		     
+		    _debug("UserAgent: Xfer subscription 100/Accepted received...\n");
+		}
+		*/
+	}
+	/*
+	 * On incoming NOTIFY, notify application about call transfer progress.
+	 */
+	else if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_ACTIVE ||
+	          pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_TERMINATED )
+	{
+		pjsip_msg *msg;
+		pjsip_msg_body *body;
+		pjsip_status_line status_line;
+		pj_bool_t is_last;
+		pj_bool_t cont;
+		pj_status_t status;
+
+		std::string noresource;
+		std::string ringing;
+		std::string request;
+
+		noresource = "noresource";
+		ringing = "Ringing";
+
+
+		SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *> ( pjsip_evsub_get_mod_data ( sub, _mod_ua.id ) );
+
+		/* When subscription is terminated, clear the xfer_sub member of
+		 * the inv_data.
+		 */
+
+		if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_TERMINATED )
+		{
+			pjsip_evsub_set_mod_data ( sub, _mod_ua.id, NULL );
+			_debug ( "UserAgent: Xfer client subscription terminated\n" );
+
+		}
+
+		if ( !link || !event )
+		{
+			/* Application is not interested with call progress status */
+			_debug ( "UserAgent: Either link or event is empty!\n" );
+			return;
+		}
+
+
+
+		/* This better be a NOTIFY request */
+		if ( event->type == PJSIP_EVENT_TSX_STATE &&
+		        event->body.tsx_state.type == PJSIP_EVENT_RX_MSG )
+		{
+
+			pjsip_rx_data *rdata;
+
+			rdata = event->body.tsx_state.src.rdata;
+
+
+			/* Check if there's body */
+			msg = rdata->msg_info.msg;
+			body = msg->body;
+			if ( !body )
+			{
+				// if (call->getCallConfiguration () == Call::IPtoIP) {
+				//   _debug("UserAgent: IptoIp NOTIFY without message body\n");
+				// }
+				// else{
+				_debug ( "UserAgent: Warning! Received NOTIFY without message body\n" );
+				return;
+				// }
+			}
+
+
+
+			/* Check for appropriate content */
+			if ( pj_stricmp2 ( &body->content_type.type, "message" ) != 0 ||
+			        pj_stricmp2 ( &body->content_type.subtype, "sipfrag" ) != 0 )
+			{
+				_debug ( "UserAgent: Warning! Received NOTIFY with non message/sipfrag content\n" );
+				return;
+			}
+
+			/* Try to parse the content */
+			status = pjsip_parse_status_line ( ( char* ) body->data, body->len,
+			                                   &status_line );
+			if ( status != PJ_SUCCESS )
+			{
+				_debug ( "UserAgent: Warning! Received NOTIFY with invalid message/sipfrag content\n" );
+				return;
+			}
+
+		}
+		else
+		{
+			_debug ( "UserAgent: Set code to 500!\n" );
+			status_line.code = 500;
+			status_line.reason = *pjsip_get_status_text ( 500 );
+		}
+
+
+		if ( event->body.rx_msg.rdata->msg_info.msg_buf != NULL )
+		{
+			request = event->body.rx_msg.rdata->msg_info.msg_buf;
+			if ( request.find ( noresource ) != -1 )
+			{
+				_debug ( "UserAgent: NORESOURCE for transfer!\n" );
+				link->transferStep2();
+				pjsip_evsub_terminate ( sub, PJ_TRUE );
+				return;
+			}
+
+			if ( request.find ( ringing ) != -1 )
+			{
+				_debug ( "UserAgent: transfered call RINGING!\n" );
+				link->transferStep2();
+				pjsip_evsub_terminate ( sub, PJ_TRUE );
+				return;
+			}
+		}
+
+
+		// Get current call
+		SIPCall *call = dynamic_cast<SIPCall *> ( link->getCall ( Manager::instance().getCurrentCallId() ) );
+		if ( !call )
+		{
+			_debug ( "UserAgent: Call doesn't exit!\n" );
+			return;
+		}
+
+
+		/* Notify application */
+		is_last = ( pjsip_evsub_get_state ( sub ) ==PJSIP_EVSUB_STATE_TERMINATED );
+		cont = !is_last;
+
+		if ( status_line.code/100 == 2 )
+		{
+
+			_debug ( "UserAgent: Try to stop rtp!\n" );
+			pjsip_tx_data *tdata;
+
+			status = pjsip_inv_end_session ( call->getInvSession(), PJSIP_SC_GONE, NULL, &tdata );
+			if ( status != PJ_SUCCESS )
+			{
+				_debug ( "UserAgent: Fail to create end session msg!\n" );
+			}
+			else
+			{
+				status = pjsip_inv_send_msg ( call->getInvSession(), tdata );
+				if ( status != PJ_SUCCESS )
+					_debug ( "UserAgent: Fail to send end session msg!\n" );
+			}
+
+			link->transferStep2();
+			cont = PJ_FALSE;
+		}
+
+		if ( !cont )
+		{
+			pjsip_evsub_set_mod_data ( sub, _mod_ua.id, NULL );
+		}
+
+	}
+
+}
+
+
+void xfer_svr_cb ( pjsip_evsub *sub, pjsip_event *event )
+{
+
+	PJ_UNUSED_ARG ( event );
+
+	/*
+	 * When subscription is terminated, clear the xfer_sub member of
+	 * the inv_data.
+	 */
+	if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_TERMINATED )
+	{
+		SIPCall *call;
+
+		call = ( SIPCall* ) pjsip_evsub_get_mod_data ( sub, _mod_ua.id );
+		if ( !call )
+			return;
+
+		pjsip_evsub_set_mod_data ( sub, _mod_ua.id, NULL );
+		call->setXferSub ( NULL );
+
+		_debug ( "UserAgent: Xfer server subscription terminated\n" );
+	}
+}
+
+void on_rx_offer ( pjsip_inv_session *inv, const pjmedia_sdp_session *offer )
+{
 
 #ifdef CAN_REINVITE
-        _debug ("reinvite                                                  SIP\n");
+	_debug ( "reinvite                                                  SIP\n" );
 
-        SIPCall *call;
-        pj_status_t status;
-        AccountID accId;
-        SIPVoIPLink *link;
+	SIPCall *call;
+	pj_status_t status;
+	AccountID accId;
+	SIPVoIPLink *link;
 
-        call = (SIPCall*)inv->mod_data[getModId()];
-        if (!call)
-            return;
+	call = ( SIPCall* ) inv->mod_data[getModId() ];
+	if ( !call )
+		return;
 
-        accId = Manager::instance().getAccountFromCall(call->getCallId());
-        link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink(accId));
+	accId = Manager::instance().getAccountFromCall ( call->getCallId() );
+	link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) );
 
-        call->getLocalSDP()->receiving_initial_offer( (pjmedia_sdp_session*)offer);
-        status=pjsip_inv_set_sdp_answer( call->getInvSession(), call->getLocalSDP()->get_local_sdp_session() );
-        if (link)
-            link->handle_reinvite (call);
+	call->getLocalSDP()->receiving_initial_offer ( ( pjmedia_sdp_session* ) offer );
+	status=pjsip_inv_set_sdp_answer ( call->getInvSession(), call->getLocalSDP()->get_local_sdp_session() );
+	if ( link )
+		link->handle_reinvite ( call );
 #endif
 
-    }
-
-    void handle_incoming_options (pjsip_rx_data *rdata) {
-        
-        pjsip_tx_data *tdata;
-        pjsip_response_addr res_addr;
-        const pjsip_hdr *cap_hdr;
-        pj_status_t status;
-
-        /* Create basic response. */
-        status = pjsip_endpt_create_response(_endpt, rdata, PJSIP_SC_OK, NULL, &tdata);
-        if (status != PJ_SUCCESS) {
-            return;
-        }
-        
-        /* Add Allow header */
-        cap_hdr = pjsip_endpt_get_capability(_endpt, PJSIP_H_ALLOW, NULL);
-        if (cap_hdr) {
-            pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, cap_hdr));
-        }
-
-        /* Add Accept header */
-        cap_hdr = pjsip_endpt_get_capability(_endpt, PJSIP_H_ACCEPT, NULL);
-        if (cap_hdr) {
-            pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, cap_hdr));
-        }
-
-        /* Add Supported header */
-        cap_hdr = pjsip_endpt_get_capability(_endpt, PJSIP_H_SUPPORTED, NULL);
-        if (cap_hdr) {
-            pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, cap_hdr));
-        }
-
-        /* Add Allow-Events header from the evsub module */
-        cap_hdr = pjsip_evsub_get_allow_events_hdr(NULL);
-        if (cap_hdr) {
-            pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, cap_hdr));
-        }
-
-        /* Send response statelessly */
-        pjsip_get_response_addr(tdata->pool, rdata, &res_addr);
-        status = pjsip_endpt_send_response(_endpt, &res_addr, tdata, NULL, NULL);
-        if (status != PJ_SUCCESS)
-            pjsip_tx_data_dec_ref(tdata);
-    }
-
-    /*****************************************************************************************************************/
-
-
-    bool setCallAudioLocal(SIPCall* call, std::string localIP, bool stun, std::string server) {
-        // Setting Audio
-        unsigned int callLocalAudioPort = RANDOM_LOCAL_PORT;
-        unsigned int callLocalExternAudioPort = callLocalAudioPort;
-        if (stun) {
-            // If use Stun server
-            if (Manager::instance().behindNat(server, callLocalAudioPort)) {
-                callLocalExternAudioPort = Manager::instance().getFirewallPort();
-            }
-        }
-        _debug("            Setting local audio port to: %d\n", callLocalAudioPort);
-        _debug("            Setting local audio port (external) to: %d\n", callLocalExternAudioPort);
-
-        // Set local audio port for SIPCall(id)
-        call->setLocalIp(localIP);
-        call->setLocalAudioPort(callLocalAudioPort);
-        call->setLocalExternAudioPort(callLocalExternAudioPort);
-
-        call->getLocalSDP()->attribute_port_to_all_media (callLocalExternAudioPort);
-
-        return true;
-    }
-
-    std::string fetch_header_value (pjsip_msg *msg, std::string field) {
-
-        pj_str_t name;
-        pjsip_generic_string_hdr * hdr;
-        std::string value, url;
-        size_t pos;
-
-        std::cout << "fetch header value" << std::endl;
-
-        /* Convert the field name into pjsip type */
-        name = pj_str ((char*)field.c_str());
-
-        /* Get the header value and convert into string*/
-        hdr = (pjsip_generic_string_hdr*) pjsip_msg_find_hdr_by_name (msg, &name, NULL);
-
-        if (!hdr)
-            return "";
-    
-        value = hdr->hvalue.ptr;
-        if ( (pos=value.find ("\n")) == std::string::npos) {
-            return "";
-        }
-        
-        url = value.substr (0, pos);
-        return url;
-    } 
+}
+
+void handle_incoming_options ( pjsip_rx_data *rdata )
+{
+
+	pjsip_tx_data *tdata;
+	pjsip_response_addr res_addr;
+	const pjsip_hdr *cap_hdr;
+	pj_status_t status;
+
+	/* Create basic response. */
+	status = pjsip_endpt_create_response ( _endpt, rdata, PJSIP_SC_OK, NULL, &tdata );
+	if ( status != PJ_SUCCESS )
+	{
+		return;
+	}
+
+	/* Add Allow header */
+	cap_hdr = pjsip_endpt_get_capability ( _endpt, PJSIP_H_ALLOW, NULL );
+	if ( cap_hdr )
+	{
+		pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) );
+	}
+
+	/* Add Accept header */
+	cap_hdr = pjsip_endpt_get_capability ( _endpt, PJSIP_H_ACCEPT, NULL );
+	if ( cap_hdr )
+	{
+		pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) );
+	}
+
+	/* Add Supported header */
+	cap_hdr = pjsip_endpt_get_capability ( _endpt, PJSIP_H_SUPPORTED, NULL );
+	if ( cap_hdr )
+	{
+		pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) );
+	}
+
+	/* Add Allow-Events header from the evsub module */
+	cap_hdr = pjsip_evsub_get_allow_events_hdr ( NULL );
+	if ( cap_hdr )
+	{
+		pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) );
+	}
+
+	/* Send response statelessly */
+	pjsip_get_response_addr ( tdata->pool, rdata, &res_addr );
+	status = pjsip_endpt_send_response ( _endpt, &res_addr, tdata, NULL, NULL );
+	if ( status != PJ_SUCCESS )
+		pjsip_tx_data_dec_ref ( tdata );
+}
+
+/*****************************************************************************************************************/
+
+
+bool setCallAudioLocal ( SIPCall* call, std::string localIP, bool stun, std::string server )
+{
+	// Setting Audio
+	unsigned int callLocalAudioPort = RANDOM_LOCAL_PORT;
+	unsigned int callLocalExternAudioPort = callLocalAudioPort;
+	if ( stun )
+	{
+		// If use Stun server
+		if ( Manager::instance().behindNat ( server, callLocalAudioPort ) )
+		{
+			callLocalExternAudioPort = Manager::instance().getFirewallPort();
+		}
+	}
+	_debug ( "            Setting local audio port to: %d\n", callLocalAudioPort );
+	_debug ( "            Setting local audio port (external) to: %d\n", callLocalExternAudioPort );
+
+	// Set local audio port for SIPCall(id)
+	call->setLocalIp ( localIP );
+	call->setLocalAudioPort ( callLocalAudioPort );
+	call->setLocalExternAudioPort ( callLocalExternAudioPort );
+
+	call->getLocalSDP()->attribute_port_to_all_media ( callLocalExternAudioPort );
+
+	return true;
+}
+
+std::string fetch_header_value ( pjsip_msg *msg, std::string field )
+{
+
+	pj_str_t name;
+	pjsip_generic_string_hdr * hdr;
+	std::string value, url;
+	size_t pos;
+
+	std::cout << "fetch header value" << std::endl;
+
+	/* Convert the field name into pjsip type */
+	name = pj_str ( ( char* ) field.c_str() );
+
+	/* Get the header value and convert into string*/
+	hdr = ( pjsip_generic_string_hdr* ) pjsip_msg_find_hdr_by_name ( msg, &name, NULL );
+
+	if ( !hdr )
+		return "";
+
+	value = hdr->hvalue.ptr;
+	if ( ( pos=value.find ( "\n" ) ) == std::string::npos )
+	{
+		return "";
+	}
+
+	url = value.substr ( 0, pos );
+	return url;
+}
 
 
diff --git a/sflphone-common/src/sipvoiplink.h b/sflphone-common/src/sipvoiplink.h
index 56d17b4b979dc98b20090f316c66fcdae83da380..028fcd8a2fd6173135816df5c1682348813daaa4 100644
--- a/sflphone-common/src/sipvoiplink.h
+++ b/sflphone-common/src/sipvoiplink.h
@@ -42,7 +42,7 @@ class AudioRtp;
 #define RANDOM_SIP_PORT   rand() % 64000 + 1024
 
 // To set the verbosity. From 0 (min) to 6 (max)
-#define PJ_LOG_LEVEL 6
+#define PJ_LOG_LEVEL 0
 
 /**
  * @file sipvoiplink.h
diff --git a/sflphone-common/test/rtpTest.cpp b/sflphone-common/test/rtpTest.cpp
index 335bb0a40bed53f92411265d2f66a9306bae03a1..1f058d1ec87114d879df4c0355e01a9a72ee062c 100644
--- a/sflphone-common/test/rtpTest.cpp
+++ b/sflphone-common/test/rtpTest.cpp
@@ -20,6 +20,13 @@
 #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 "rtpTest.h"
@@ -33,19 +40,45 @@ using std::endl;
 
 void RtpTest::setUp(){
 
+  _debug("------ Set up rtp test------\n");
+
     Manager::instance().initConfigFile();
     Manager::instance().init();
 
+    pjsipInit();
+
     CallID cid = "123456";
-        
-    audiortp = new AudioRtp();
 
-    sipcall = new SIPCall(cid, Call::Incoming, NULL);
+    sipcall = new SIPCall(cid, Call::Incoming, _pool);
+    
+    sipcall->setLocalIp("127.0.0.1");
+    sipcall->setLocalAudioPort(RANDOM_LOCAL_PORT);
+    sipcall->setLocalExternAudioPort(RANDOM_LOCAL_PORT);
+
+    
 }
 
-void RtpTest::testRtpInit()
+bool RtpTest::pjsipInit(){
+
+    // Create memory cache for pool
+    pj_caching_pool_init(&_cp, &pj_pool_factory_default_policy, 0);
+
+    // Create memory pool for application. 
+    _pool = pj_pool_create(&_cp.factory, "rtpTest", 4000, 4000, NULL);
+
+    if (!_pool) {
+        _debug("----- RtpTest: Could not initialize pjsip memory pool ------\n");
+        return PJ_ENOMEM;
+    }
+
+}
+
+
+void RtpTest::testRtpInitClose()
 {
 
+    audiortp = new AudioRtp();
+
     _debug("------ void RtpTest::testRtpInit() ------\n");
     try {
 
@@ -54,17 +87,16 @@ void RtpTest::testRtpInit()
 
     } catch(...) {
         
-        _debug("!!! Exception occured while Oppenning Rtp \n");
+        _debug("!!! Exception occured while Oppenning Rtp !!!\n");
 	
     }
 
-}
+    CPPUNIT_ASSERT(audiortp != NULL);
     
+    _debug("------ Finilize Rtp Initialization ------ \n");
 
-void RtpTest::testRtpClose()
-{
 
-  _debug("------ RtpTest::testRtpClose() ------");
+    _debug("------ RtpTest::testRtpClose() ------\n");
 
     try {
       _debug("------ Close Rtp Session -------\n");  
@@ -72,14 +104,46 @@ void RtpTest::testRtpClose()
 
     } catch(...) {
 
-        _debug("!!! Exception occured while closing Rtp \n");
+        _debug("!!! Exception occured while closing Rtp !!!\n");
+
+    }
+
+    delete audiortp;  audiortp = NULL;
+
+}
+
+void RtpTest::testRtpThread()
+{
+
+    _debug("------ void RtpTest::testRtpThread ------\n");
+
+    
+
+    if(rtpthread != 0){
+        _debug("!!! Rtp Thread already exists..., stopping it\n"); 
+	delete rtpthread;  rtpthread = 0;
+    }
+
+    CPPUNIT_ASSERT(rtpthread == 0);
+    // CPPUNIT_ASSERT(rtpthread->_sym == NULL);
+
+    try {
+
+        rtpthread = new AudioRtpRTX(sipcall, true);
+	
+    } catch(...) {
+
+        _debug("!!! Exception occured while instanciating AudioRtpRTX !!!\n");
 
     }
 
+    CPPUNIT_ASSERT(rtpthread == 0);
+
+    delete rtpthread;  rtpthread = 0;
 }
 
 
 void RtpTest::tearDown(){
 
-    delete audiortp;  audiortp = NULL;
+    delete sipcall;   sipcall = NULL;
 }
diff --git a/sflphone-common/test/rtpTest.h b/sflphone-common/test/rtpTest.h
index b2d314a1c2968f2e1aa082bc3018ae7eb5158f09..dec1b9798694eea926e6d9979ba3e6716b77b492 100644
--- a/sflphone-common/test/rtpTest.h
+++ b/sflphone-common/test/rtpTest.h
@@ -25,11 +25,24 @@
 
 #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/audiortp.h"
 #include "../src/call.h"
 #include "../src/sipcall.h"
+#include "../src/sipvoiplink.h"
 
 #include "config/config.h"
 #include "user_cfg.h"
@@ -44,7 +57,9 @@
 #ifndef _RTP_TEST_
 #define _RTP_TEST_
 
-
+class AudioRtp;
+class AudioRtpRTX;
+class SIPVoIPLink;
 
 class RtpTest : public CppUnit::TestCase {
 
@@ -52,8 +67,8 @@ class RtpTest : public CppUnit::TestCase {
      * Use cppunit library macros to add unit test the factory
      */
     CPPUNIT_TEST_SUITE( RtpTest );
-        CPPUNIT_TEST( testRtpInit );
-	CPPUNIT_TEST( testRtpClose );
+        CPPUNIT_TEST( testRtpInitClose );
+	CPPUNIT_TEST( testRtpThread );
     CPPUNIT_TEST_SUITE_END();
 
     public:
@@ -71,9 +86,12 @@ class RtpTest : public CppUnit::TestCase {
          */
         inline void tearDown();
 
-        void testRtpInit();
+	bool pjsipInit();
+
+        void testRtpInitClose();
+
+	void testRtpThread();
 
-	void testRtpClose();
 
     private:
 
@@ -83,8 +101,14 @@ class RtpTest : public CppUnit::TestCase {
 
         AudioRtp *audiortp;
 
+	AudioRtpRTX *rtpthread;
+
 	SIPCall *sipcall;
 
+	pj_caching_pool _cp;
+
+	pj_pool_t *_pool;
+
 };
 
 /* Register our test module */
diff --git a/tools/build-system/bin/git-dch b/tools/build-system/bin/git-dch
new file mode 100755
index 0000000000000000000000000000000000000000..f9ee5bc56f14d320c63c27da987ca0029fbb244f
--- /dev/null
+++ b/tools/build-system/bin/git-dch
@@ -0,0 +1,404 @@
+#!/usr/bin/python -u
+# vim: set fileencoding=utf-8 :
+#
+# (C) 2007,2008 Guido Guenther <agx@sigxcpu.org>
+#    This program is free software; you can redistribute it and/or modify
+#    it under the terms of the GNU General Public License as published by
+#    the Free Software Foundation; either version 2 of the License, or
+#    (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU General Public License for more details.
+#
+#    You should have received a copy of the GNU General Public License
+#    along with this program; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+"""Generate Debian changelog entries from git commit messages"""
+
+import sys
+import re
+import os.path
+import shutil
+import subprocess
+import gbp.command_wrappers as gbpc
+from gbp.git_utils import (GitRepositoryError, GitRepository, build_tag)
+from gbp.config import GbpOptionParser, GbpOptionGroup
+from gbp.errors import GbpError
+from gbp.deb_utils import parse_changelog
+from gbp.command_wrappers import (Command, CommandExecFailed)
+
+snapshot_re = re.compile("\s*\*\* SNAPSHOT build @(?P<commit>[a-z0-9]+)\s+\*\*")
+author_re = re.compile('Author: (?P<author>.*) <(?P<email>.*)>')
+bug_r = r'(?:bug)?\#?\s?\d+'
+bug_re = re.compile(bug_r, re.I)
+
+def system(cmd):
+    try:
+        Command(cmd, shell=True)()
+    except CommandExecFailed:
+        raise GbpError
+
+
+def escape_commit(msg):
+    return msg.replace('"','\\\"').replace("$","\$").replace("`","\`")
+
+
+def spawn_dch(msg='', author=None, email=None, newversion=False, version=None, release=False, distribution=None):
+    distopt = ""
+    versionopt = ""
+    env = ""
+
+    if newversion:
+        if version:
+            versionopt = '--newversion=%s' % version
+        else:
+            versionopt = '-i'
+    elif release:
+        versionopt = "--release"
+        msg = None
+
+    if author and email:
+        env = """DEBFULLNAME="%s" DEBEMAIL="%s" """ % (author, email)
+
+    if distribution:
+        distopt = "--distribution=%s" % distribution
+
+    cmd = '%(env)s dch --no-auto-nmu  %(distopt)s %(versionopt)s ' % locals()
+    if type(msg) == type(''):
+        cmd += '"%s"' % escape_commit(msg)
+    system(cmd)
+
+
+def add_changelog_entry(msg, author, email):
+    "add aa single changelog entry"
+    spawn_dch(msg=msg, author=author, email=email)
+
+
+def add_changelog_section(msg, distribution, author=None, email=None, version=None):
+    "add a new changelog section"
+    spawn_dch(msg=msg, newversion= True, version=version, author=author, email=email, distribution=distribution)
+
+
+def fixup_trailer(repo, git_author=False):
+    """fixup the changelog trailer's comitter and email address - it might
+    otherwise point to the last git committer instead of the person creating
+    the changelog"""
+    author = email = None
+    if git_author:
+        try: author = repo.get_config('user.name')
+        except KeyError: pass
+
+        try: email = repo.get_config('user.email')
+        except KeyError: pass
+
+    spawn_dch(msg='', author=author, email=email)
+
+
+def head_commit():
+    """get the full sha1 of the last commit on HEAD"""
+    commit = subprocess.Popen([ 'git', 'log', 'HEAD^..' ], stdout=subprocess.PIPE).stdout
+    sha = commit.readline().split()[-1]
+    return sha
+
+
+def snapshot_version(version):
+    """
+    get the current release and snapshot version
+    Format is <debian-version>~<release>.gbp<short-commit-id>
+    """
+    try:
+        (release, suffix) = version.rsplit('~', 1)
+        (snapshot, commit)  = suffix.split('.', 1)
+        if not commit.startswith('gbp'):
+            raise ValueError
+        else:
+            snapshot = int(snapshot)
+    except ValueError: # not a snapshot release
+        release = version
+        snapshot = 0
+    return release, snapshot
+
+
+def mangle_changelog(changelog, cp, snapshot=''):
+    """
+    Mangle changelog to either add or remove snapshot markers
+
+    @param snapshot: SHA1 if snapshot header should be added/maintained, empty if it should be removed
+    @type  snapshot: str
+    """
+    try:
+        tmpfile = '%s.%s' % (changelog, snapshot)
+        cw = file(tmpfile, 'w')
+        cr = file(changelog, 'r')
+
+        cr.readline() # skip version and empty line
+        cr.readline()
+        print >>cw, "%(Source)s (%(MangledVersion)s) %(Distribution)s; urgency=%(urgency)s\n" % cp
+
+        line = cr.readline()
+        if snapshot_re.match(line):
+            cr.readline() # consume the empty line after the snapshot header
+            line = ''
+
+        if snapshot:
+            print >>cw, "  ** SNAPSHOT build @%s **\n" % snapshot
+
+        if line:
+            print >>cw, line.rstrip()
+        shutil.copyfileobj(cr, cw)
+        cw.close()
+        cr.close()
+        os.unlink(changelog)
+        os.rename(tmpfile, changelog)
+    except OSError, e:
+        raise GbpError, "Error mangling changelog %s" % e
+
+
+def do_release(changelog, cp):
+    "remove the snapshot header and set the distribution"
+    (release, snapshot) = snapshot_version(cp['Version'])
+    if snapshot:
+        cp['MangledVersion'] = release
+        mangle_changelog(changelog, cp)
+    # <julien.bonjean@savoirfairelinux.com>
+    # prevent doing a release
+    # spawn_dch(release=True)
+
+
+def do_snapshot(changelog, next_snapshot):
+    """
+    Add new snapshot banner to most recent changelog section. The next snapshot
+    number is calculated by eval()'ing next_snapshot
+    """
+    # commit = head_commit()
+
+    cp = parse_changelog(changelog)
+
+    # <julien.bonjean@savoirfairelinux.com>
+    # clean version before generate snapshot
+    version=cp['Version']
+    try:
+        (release, suffix) = version.rsplit('~', 1)
+    except:
+        pass
+    try:
+        (snapshot, commit)  = suffix.split('.', 1) 
+	stripped = str(int(snapshot))
+    except:
+	version=release
+    commit = head_commit()
+
+    (release, snapshot) = snapshot_version(version)
+    snapshot = int(eval(next_snapshot))
+
+    suffix = "%d.gbp%s" % (snapshot, "".join(commit[0:6]))
+    cp['MangledVersion'] = "%s~%s" % (release, suffix)
+
+    mangle_changelog(changelog, cp, commit)
+    return snapshot, commit
+
+
+def get_author(commit):
+    """get the author from a commit message"""
+    for line in commit:
+        m = author_re.match(line)
+        if m:
+            return m.group('author'), m.group('email')
+
+
+def parse_commit(repo, commitid, options):
+    """parse a commit and return message and author"""
+    msg = ''
+    thanks = ''
+    closes = ''
+    bugs = {}
+    bts_closes = re.compile(r'(?P<bts>%s):\s+%s' % (options.meta_closes, bug_r), re.I)
+
+    commit = repo.show(commitid)
+    author, email = get_author(commit)
+    if not author:
+        raise GbpError, "can't parse author of commit %s" % commit
+    for line in commit:
+        if line.startswith('    '): # commit body
+            line = line[4:]
+            m = bts_closes.match(line)
+            if m:
+                bug_nums = [ bug.strip() for bug in bug_re.findall(line, re.I) ]
+                try:
+                    bugs[m.group('bts')] += bug_nums
+                except KeyError:
+                    bugs[m.group('bts')] = bug_nums
+            elif line.startswith('Thanks: '):
+                thanks = line.split(' ', 1)[1].strip()
+            else: # normal commit message
+                if options.short and msg:
+                    continue
+                elif line.strip(): # don't add all whitespace lines
+                    msg += line
+        # start of diff output:
+        elif line.startswith('diff '):
+            break
+    if options.meta:
+        for bts in bugs:
+            closes += '(%s: %s) ' % (bts, ', '.join(bugs[bts]))
+        if thanks:
+            thanks = '- thanks to %s' % thanks
+        msg += closes + thanks
+    if options.idlen:
+        msg = "[%s] " % commitid[0:options.idlen] + msg
+    return msg, (author, email)
+
+
+def shortlog_to_dch(repo, commits, options):
+    """convert the changes in git shortlog format to debian changelog format"""
+    author = 'Unknown'
+
+    for commit in commits:
+        msg, (author, email) = parse_commit(repo, commit, options)
+        add_changelog_entry(msg, author, email)
+
+
+def guess_snapshot_commit(cp):
+    """guess the last commit documented in the changelog from the snapshot banner"""
+    sr = re.search(snapshot_re, cp['Changes'])
+    if sr:
+        return sr.group('commit')
+
+
+def main(argv):
+    ret = 0
+    changelog = 'debian/changelog'
+    until = 'HEAD'
+    found_snapshot_header = False
+    first_commit = None
+
+    parser = GbpOptionParser(command=os.path.basename(argv[0]), prefix='',
+                             usage='%prog [options] paths')
+    range_group = GbpOptionGroup(parser, "commit range options", "which commits to add to the changelog")
+    version_group = GbpOptionGroup(parser, "release & version number options", "what version number and release to use")
+    commit_group = GbpOptionGroup(parser, "commit message formatting", "howto format the changelog entries")
+    naming_group = GbpOptionGroup(parser, "branch and tag naming", "branch names and tag formats")
+    parser.add_option_group(range_group)
+    parser.add_option_group(version_group)
+    parser.add_option_group(commit_group)
+    parser.add_option_group(naming_group)
+
+    naming_group.add_config_file_option(option_name="debian-branch", dest="debian_branch")
+    naming_group.add_config_file_option(option_name="upstream-tag", dest="upstream_tag")
+    naming_group.add_config_file_option(option_name="debian-tag", dest="debian_tag")
+    naming_group.add_config_file_option(option_name="snapshot-number", dest="snapshot_number",
+                      help="expression to determine the next snapshot number, default is '%(snapshot-number)s'")
+    parser.add_config_file_option(option_name="git-log", dest="git_log",
+                      help="options to pass to git-log, default is '%(git-log)s'")
+    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
+                      help="verbose command execution")
+    range_group.add_option("-s", "--since", dest="since", help="commit to start from (e.g. HEAD^^^, debian/0.4.3)")
+    range_group.add_option("-a", "--auto", action="store_true", dest="auto", default=False,
+                      help="autocomplete changelog from last snapshot or tag")
+    version_group.add_option("-R", "--release", action="store_true", dest="release", default=False,
+                      help="mark as release")
+    version_group.add_option("-S", "--snapshot", action="store_true", dest="snapshot", default=False,
+                      help="mark as snapshot build")
+    version_group.add_option("-N", "--new-version", dest="new_version",
+                      help="use this as base for the new version number")
+    version_group.add_config_file_option(option_name="git-author", dest="git_author", action="store_true")
+    version_group.add_config_file_option(option_name="no-git-author", dest="git_author", action="store_false")
+    commit_group.add_config_file_option(option_name="meta", dest="meta",
+                      help="parse meta tags in commit messages, default is '%(meta)s'", action="store_true")
+    commit_group.add_config_file_option(option_name="meta-closes", dest="meta_closes",
+                      help="Meta tags for the bts close commands, default is '%(meta-closes)s'")
+    commit_group.add_option("--full", action="store_false", dest="short", default=True,
+                      help="include the full commit message instead of only the first line")
+    commit_group.add_config_file_option(option_name="id-length", dest="idlen",
+                      help="include N digits of the commit id in the changelog entry, default is '%(id-length)s'",
+                      type="int", metavar="N")
+    (options, args) = parser.parse_args(argv[1:])
+
+    if options.snapshot and options.release:
+        parser.error("'--snapshot' and '--release' are incompatible options")
+
+    if options.since and options.auto:
+        parser.error("'--since' and '--auto' are incompatible options")
+
+    try:
+        if options.verbose:
+            gbpc.Command.verbose = True
+
+        try:
+            repo = GitRepository('.')
+        except GitRepositoryError:
+            raise GbpError, "%s is not a git repository" % (os.path.abspath('.'))
+
+        branch = repo.get_branch()
+        if options.debian_branch != branch:
+            print >>sys.stderr, "You are not on branch '%s' but on '%s'" % (options.debian_branch, branch)
+            raise GbpError, "Use --debian-branch to set the branch to pick changes from"
+
+        cp = parse_changelog(changelog)
+
+        if options.since:
+            since = options.since
+        else:
+            since = ''
+            if options.auto:
+                since = guess_snapshot_commit(cp)
+                if since:
+                    print "Continuing from commit '%s'" % since
+                    found_snapshot_header = True
+                else:
+                    print "Couldn't find snapshot header, using version info"
+            if not since:
+                since = build_tag(options.debian_tag, cp['Version'])
+
+        if args:
+            print "Only looking for changes on '%s'" % " ".join(args)
+        commits = repo.commits(since, until, " ".join(args), options.git_log.split(" "))
+
+        # add a new changelog section if:
+        if cp['Distribution'] != "UNRELEASED" and not found_snapshot_header and commits:
+            # the last version was a release and we have pending commits
+            add_section = True
+        elif options.new_version or not found_snapshot_header:
+            # the user wants to force a new version or switch to snapshot mode
+            add_section = True
+        else:
+            add_section = False
+
+        if add_section:
+            if commits:
+                first_commit = commits[0]
+                commits = commits[1:]
+                commit_msg, (commit_author, commit_email) = parse_commit(repo, first_commit, options)
+            else:
+                commit_msg = "UNRELEASED"
+                commit_author = None
+                commit_email = None
+            add_changelog_section(distribution="UNRELEASED", msg=commit_msg,
+                                  version=options.new_version, author=commit_author,
+                                  email=commit_email)
+
+        if commits:
+            shortlog_to_dch(repo, commits, options)
+            fixup_trailer(repo, git_author=options.git_author)
+        elif not first_commit:
+            print "No changes detected from %s to %s." % (since, until)
+
+        if options.release:
+            do_release(changelog, cp)
+        elif options.snapshot:
+            (snap, version) = do_snapshot(changelog, options.snapshot_number)
+            print "Changelog has been prepared for snapshot #%d at %s" % (snap, version)
+
+    except (GbpError, GitRepositoryError), err:
+        if len(err.__str__()):
+            print >>sys.stderr, err
+        ret = 1
+    return ret
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
+
+# vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·:
diff --git a/tools/build-system/distributions/ubuntu/debian-sflphone-client-gnome/changelog b/tools/build-system/distributions/ubuntu/debian-sflphone-client-gnome/changelog
index ec28d0e6b3f8c27e66f305a6e0d744234dbf57d5..b1c23da835fa6c25603851b9160396e4917e544c 100644
--- a/tools/build-system/distributions/ubuntu/debian-sflphone-client-gnome/changelog
+++ b/tools/build-system/distributions/ubuntu/debian-sflphone-client-gnome/changelog
@@ -1,7 +1,15 @@
-sflphone-client-gnome (0.9.5-SYSVER~snapshot1243396910) SYSTEM; urgency=low
-
-    ** SNAPSHOT 1243396910 **
-
+sflphone-client-gnome (0.9.5-SYSVER~snapshot1243483310) SYSTEM; urgency=low
+
+    ** SNAPSHOT 1243483310 **
+
+  * [#1317] Remove spec files from configure
+  * [#1317] Added missing prefix
+  * [#1430] Add a connection reference which most likely belong to
+    libdbus
+  * [#1430] Use shared connection instead of private
+  * [#1317] Fixed packaging rules
+  * [#1317] Updated autogen
+  * Updated autogen.sh for pjsip
   * [#1317] Fixed pjsip lib dirs
   * [#1317] Updated debian packaging for new pjsip configuration script
   * [#1317] Switch to autogenerated guess and sub files
@@ -84,7 +92,7 @@ sflphone-client-gnome (0.9.5-SYSVER~snapshot1243396910) SYSTEM; urgency=low
   * Config Dialog almost finished.
   * Base of QT client
 
- -- SFLphone Automatic Build System <team@sflphone.org>  Wed, 27 May 2009 00:02:36 -0400
+ -- SFLphone Automatic Build System <team@sflphone.org>  Thu, 28 May 2009 00:02:48 -0400
 
 sflphone-client-gnome (0.9.5-SYSVER) SYSTEM; urgency=low
 
diff --git a/tools/build-system/distributions/ubuntu/debian-sflphone-common/changelog b/tools/build-system/distributions/ubuntu/debian-sflphone-common/changelog
index 12f5f0155c1ba7d8ec87418554accd2401ce5879..ba0cd95b1fcd2b1af7074b354674f6d64bb8cf34 100644
--- a/tools/build-system/distributions/ubuntu/debian-sflphone-common/changelog
+++ b/tools/build-system/distributions/ubuntu/debian-sflphone-common/changelog
@@ -1,7 +1,15 @@
-sflphone-common (0.9.5-SYSVER~snapshot1243396910) SYSTEM; urgency=low
-
-    ** SNAPSHOT 1243396910 **
-
+sflphone-common (0.9.5-SYSVER~snapshot1243483310) SYSTEM; urgency=low
+
+    ** SNAPSHOT 1243483310 **
+
+  * [#1317] Remove spec files from configure
+  * [#1317] Added missing prefix
+  * [#1430] Add a connection reference which most likely belong to
+    libdbus
+  * [#1430] Use shared connection instead of private
+  * [#1317] Fixed packaging rules
+  * [#1317] Updated autogen
+  * Updated autogen.sh for pjsip
   * [#1317] Fixed pjsip lib dirs
   * [#1317] Updated debian packaging for new pjsip configuration script
   * [#1317] Switch to autogenerated guess and sub files
@@ -84,7 +92,7 @@ sflphone-common (0.9.5-SYSVER~snapshot1243396910) SYSTEM; urgency=low
   * Config Dialog almost finished.
   * Base of QT client
 
- -- SFLphone Automatic Build System <team@sflphone.org>  Wed, 27 May 2009 00:02:13 -0400
+ -- SFLphone Automatic Build System <team@sflphone.org>  Thu, 28 May 2009 00:02:20 -0400
 
 sflphone-common (0.9.5-SYSVER) SYSTEM; urgency=low