Index: /pjproject/trunk/build.symbian/pjlib_util.mmp
===================================================================
--- /pjproject/trunk/build.symbian/pjlib_util.mmp	(revision 4460)
+++ /pjproject/trunk/build.symbian/pjlib_util.mmp	(revision 4461)
@@ -33,4 +33,7 @@
 //
 SOURCE	base64.c
+SOURCE	cli.c
+SOURCE	cli_console.c
+SOURCE	cli_telnet.c
 SOURCE	crc32.c
 SOURCE	dns.c
Index: /pjproject/trunk/pjlib-util/include/pjlib-util.h
===================================================================
--- /pjproject/trunk/pjlib-util/include/pjlib-util.h	(revision 4460)
+++ /pjproject/trunk/pjlib-util/include/pjlib-util.h	(revision 4461)
@@ -64,3 +64,6 @@
 #include <pjlib-util/http_client.h>
 
+/** CLI Telnet **/
+#include <pjlib-util/cli_telnet.h>
+
 #endif	/* __PJLIB_UTIL_H__ */
Index: /pjproject/trunk/pjlib-util/include/pjlib-util/cli_telnet.h
===================================================================
--- /pjproject/trunk/pjlib-util/include/pjlib-util/cli_telnet.h	(revision 4460)
+++ /pjproject/trunk/pjlib-util/include/pjlib-util/cli_telnet.h	(revision 4461)
@@ -35,4 +35,29 @@
  */
 
+ /**
+ * This structure contains the information about the telnet.
+ * Application will get updated information each time the telnet is started/
+ * restarted.
+ */
+typedef struct pj_cli_telnet_info
+{
+    /**
+     * The telnet's ip address.
+     */
+    pj_str_t	ip_address;
+
+    /**
+     * The telnet's port number.
+     */
+    pj_uint16_t port;
+} pj_cli_telnet_info;
+
+/**
+ * This specifies the callback called when telnet is started
+ *
+ * @param telnet_info   The telnet runtime information.
+ *
+ */
+typedef void (*pj_cli_telnet_on_started)(pj_cli_telnet_info *telnet_info);
 
 /**
@@ -86,6 +111,12 @@
     pj_str_t prompt_str;
 
+    /**
+     * Specify the pj_cli_telnet_on_started callback.
+     *
+     * Default: empty
+     */
+    pj_cli_telnet_on_started on_started;
+
 } pj_cli_telnet_cfg;
-
 
 /**
Index: /pjproject/trunk/pjlib-util/include/pjlib-util/config.h
===================================================================
--- /pjproject/trunk/pjlib-util/include/pjlib-util/config.h	(revision 4460)
+++ /pjproject/trunk/pjlib-util/include/pjlib-util/config.h	(revision 4461)
@@ -292,5 +292,5 @@
  */
 #ifndef PJ_CLI_MAX_CMDBUF
-#   define PJ_CLI_MAX_CMDBUF		120
+#   define PJ_CLI_MAX_CMDBUF		512
 #endif
 
Index: /pjproject/trunk/pjlib-util/src/pjlib-util/cli_telnet.c
===================================================================
--- /pjproject/trunk/pjlib-util/src/pjlib-util/cli_telnet.c	(revision 4460)
+++ /pjproject/trunk/pjlib-util/src/pjlib-util/cli_telnet.c	(revision 4461)
@@ -30,4 +30,13 @@
 #include <pjlib-util/errno.h>
 #include <pjlib-util/scanner.h>
+#include <pj/addr_resolv.h>
+#include <pj/compat/socket.h>
+
+#if (defined(PJ_WIN32) && PJ_WIN32!=0) || \
+    (defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0)
+
+#define EADDRINUSE WSAEADDRINUSE 
+
+#endif
 
 #define CLI_TELNET_BUF_SIZE 256
@@ -45,4 +54,12 @@
 
 #define MAX_CLI_TELNET_OPTIONS 256
+/** Maximum retry on Telnet Restart **/
+#define MAX_RETRY_ON_TELNET_RESTART 100
+/** Minimum number of millisecond to wait before retrying to re-bind on
+ * telnet restart **/
+#define MIN_WAIT_ON_TELNET_RESTART 20
+/** Maximum number of millisecod to wait before retrying to re-bind on
+ *  telnet restart **/
+#define MAX_WAIT_ON_TELNET_RESTART 1000
 
 /**
@@ -262,5 +279,5 @@
 } cli_telnet_sess;
 
-struct cli_telnet_fe
+typedef struct cli_telnet_fe
 {
     pj_cli_front_end        base;
@@ -273,6 +290,6 @@
     pj_thread_t            *worker_thread;
     pj_bool_t               is_quitting;
-    pj_mutex_t             *mutex;
-};
+    pj_mutex_t             *mutex;    
+} cli_telnet_fe;
 
 /* Forward Declaration */
@@ -282,4 +299,7 @@
 static pj_status_t telnet_sess_send(cli_telnet_sess *sess,
                                     const pj_str_t *str);
+
+static pj_status_t telnet_start(cli_telnet_fe *fe);
+static pj_status_t telnet_restart(cli_telnet_fe *tfe);
 
 /**
@@ -646,5 +666,5 @@
     pj_str_t send_data;
     char data_str[128];
-    struct cli_telnet_fe *fe = (struct cli_telnet_fe *)sess->base.fe;
+    cli_telnet_fe *fe = (cli_telnet_fe *)sess->base.fe;
 
     send_data.ptr = &data_str[0];
@@ -670,5 +690,5 @@
     unsigned len;
     unsigned i;
-    struct cli_telnet_fe *fe = (struct cli_telnet_fe *)sess->base.fe;
+    cli_telnet_fe *fe = (cli_telnet_fe *)sess->base.fe;
 
     send_data.ptr = &data_str[0];
@@ -744,5 +764,5 @@
     pj_str_t send_data;
     char data[1028];
-    struct cli_telnet_fe *fe = (struct cli_telnet_fe *)sess->base.fe;
+    cli_telnet_fe *fe = (cli_telnet_fe *)sess->base.fe;
     const pj_cli_hint_info *hint = info->hint;
     out_parse_state parse_state = OP_NORMAL;
@@ -1319,5 +1339,5 @@
 {
     cli_telnet_sess *tsess = (cli_telnet_sess *)sess;
-    pj_mutex_t *mutex = ((struct cli_telnet_fe *)sess->fe)->mutex;
+    pj_mutex_t *mutex = ((cli_telnet_fe *)sess->fe)->mutex;
 
     pj_mutex_lock(mutex);
@@ -1335,5 +1355,5 @@
 		                const char *data, int len)
 {
-    struct cli_telnet_fe * tfe = (struct cli_telnet_fe *)fe;
+    cli_telnet_fe *tfe = (cli_telnet_fe *)fe;
     pj_cli_sess *sess;    
 
@@ -1358,5 +1378,5 @@
 static void telnet_fe_destroy(pj_cli_front_end *fe)
 {
-    struct cli_telnet_fe *tfe = (struct cli_telnet_fe *)fe;
+    cli_telnet_fe *tfe = (cli_telnet_fe *)fe;
     pj_cli_sess *sess;
 
@@ -1392,5 +1412,5 @@
 static int poll_worker_thread(void *p)
 {
-    struct cli_telnet_fe *fe = (struct cli_telnet_fe *)p;
+    cli_telnet_fe *fe = (cli_telnet_fe *)p;
 
     while (!fe->is_quitting) {
@@ -1409,7 +1429,8 @@
 			    pj_activesock_get_user_data(asock);
 
-    PJ_UNUSED_ARG(op_key);
+    PJ_UNUSED_ARG(op_key);    
 
     if (sent <= 0) {
+	TRACE_((THIS_FILE, "Error On data send"));
         pj_cli_sess_end_session(&sess->base);
         return PJ_FALSE;
@@ -1442,5 +1463,5 @@
     cli_telnet_sess *sess = (cli_telnet_sess *)
                             pj_activesock_get_user_data(asock);
-    struct cli_telnet_fe *tfe = (struct cli_telnet_fe *)sess->base.fe;
+    cli_telnet_fe *tfe = (cli_telnet_fe *)sess->base.fe;
     unsigned char *cdata = (unsigned char*)data;    
     pj_status_t is_valid = PJ_TRUE;
@@ -1449,11 +1470,11 @@
     PJ_UNUSED_ARG(remainder);
 
-    if (status != PJ_SUCCESS && status != PJ_EPENDING) {
-        pj_cli_sess_end_session(&sess->base);
-        return PJ_FALSE;
-    }
-
     if (tfe->is_quitting)
         return PJ_FALSE;
+
+    if (status != PJ_SUCCESS && status != PJ_EPENDING) {
+	TRACE_((THIS_FILE, "Error on data read %d", status));
+        return PJ_FALSE;
+    }    
 
     pj_mutex_lock(sess->smutex);
@@ -1552,11 +1573,12 @@
 				     pj_sock_t newsock,
 				     const pj_sockaddr_t *src_addr,
-				     int src_addr_len)
-{
-    struct cli_telnet_fe *fe = (struct cli_telnet_fe *)
-                                pj_activesock_get_user_data(asock);
+				     int src_addr_len,
+				     pj_status_t status)
+{
+    cli_telnet_fe *fe = (cli_telnet_fe *) pj_activesock_get_user_data(asock);
+
     pj_status_t sstatus;
     pj_pool_t *pool;
-    cli_telnet_sess *sess;
+    cli_telnet_sess *sess = NULL;
     pj_activesock_cb asock_cb;
 
@@ -1566,4 +1588,12 @@
     if (fe->is_quitting)
         return PJ_FALSE;
+
+    if (status != PJ_SUCCESS && status != PJ_EPENDING) {
+	TRACE_((THIS_FILE, "Error on data accept %d", status));
+	if (status == PJ_ESOCKETSTOP) 
+	    telnet_restart(fe);	    
+	
+        return PJ_FALSE;
+    }    
 
     /* An incoming connection is accepted, create a new session */
@@ -1658,10 +1688,7 @@
 					 pj_cli_front_end **p_fe)
 {
-    struct cli_telnet_fe *fe;
+    cli_telnet_fe *fe;
     pj_pool_t *pool;
-    pj_sock_t sock = PJ_INVALID_SOCKET;
-    pj_activesock_cb asock_cb;
-    pj_sockaddr_in addr;
-    pj_status_t sstatus;
+    pj_status_t status;   
 
     PJ_ASSERT_RETURN(cli, PJ_EINVAL);
@@ -1670,5 +1697,5 @@
                           PJ_CLI_TELNET_POOL_SIZE, PJ_CLI_TELNET_POOL_INC,
                           NULL);
-    fe = PJ_POOL_ZALLOC_T(pool, struct cli_telnet_fe);
+    fe = PJ_POOL_ZALLOC_T(pool, cli_telnet_fe);
     if (!fe)
         return PJ_ENOMEM;
@@ -1688,40 +1715,84 @@
     fe->pool = pool;
 
-    if (!fe->cfg.ioqueue) {
+    if (!fe->cfg.ioqueue) {	
         /* Create own ioqueue if application doesn't supply one */
-        sstatus = pj_ioqueue_create(pool, 8, &fe->cfg.ioqueue);
-        if (sstatus != PJ_SUCCESS)
+        status = pj_ioqueue_create(pool, 8, &fe->cfg.ioqueue);
+        if (status != PJ_SUCCESS)
             goto on_exit;
         fe->own_ioqueue = PJ_TRUE;
     }
 
-    sstatus = pj_mutex_create_recursive(pool, "mutex_telnet_fe", &fe->mutex);
-    if (sstatus != PJ_SUCCESS)
+    status = pj_mutex_create_recursive(pool, "mutex_telnet_fe", &fe->mutex);
+    if (status != PJ_SUCCESS)
         goto on_exit;
 
     /* Start telnet daemon */
-    sstatus = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, 
-                             &sock);
-    if (sstatus != PJ_SUCCESS)
+    telnet_start(fe);
+
+    pj_cli_register_front_end(cli, &fe->base);
+
+    if (p_fe)
+        *p_fe = &fe->base;
+
+    return PJ_SUCCESS;
+
+on_exit:
+    if (fe->own_ioqueue)
+        pj_ioqueue_destroy(fe->cfg.ioqueue);
+
+    if (fe->mutex)
+        pj_mutex_destroy(fe->mutex);
+
+    pj_pool_release(pool);
+    return status;
+}
+
+static pj_status_t telnet_start(cli_telnet_fe *fe)
+{
+    pj_sock_t sock = PJ_INVALID_SOCKET;
+    pj_activesock_cb asock_cb;
+    pj_sockaddr_in addr;
+    pj_status_t status;   
+    int val;
+    int restart_retry;
+    unsigned msec;
+
+    /* Start telnet daemon */
+    status = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0, &sock);
+
+    if (status != PJ_SUCCESS)
         goto on_exit;
 
     pj_sockaddr_in_init(&addr, NULL, fe->cfg.port);
 
-    sstatus = pj_sock_bind(sock, &addr, sizeof(addr));
-    if (sstatus == PJ_SUCCESS) {
-	pj_sockaddr_in addr;
-	int addr_len = sizeof(addr);
-
-	sstatus = pj_sock_getsockname(sock, &addr, &addr_len);
-	if (sstatus != PJ_SUCCESS)
+    val = 1;
+    status = pj_sock_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
+				&val, sizeof(val));
+
+    if (status != PJ_SUCCESS)
+	goto on_exit;
+
+    /* The loop is silly, but what else can we do? */
+    for (msec=MIN_WAIT_ON_TELNET_RESTART, restart_retry=0;
+	 restart_retry < MAX_RETRY_ON_TELNET_RESTART;
+	 ++restart_retry, msec=(msec<MAX_WAIT_ON_TELNET_RESTART?
+		          msec*2 : MAX_WAIT_ON_TELNET_RESTART))
+    {
+	status = pj_sock_bind(sock, &addr, sizeof(addr));
+	if (status != PJ_STATUS_FROM_OS(EADDRINUSE))
+	    break;
+	PJ_LOG(4,(THIS_FILE, "Address is still in use, retrying.."));
+	pj_thread_sleep(msec);
+    }    
+    
+    if (status == PJ_SUCCESS) {	
+	int addr_len = sizeof(addr);	
+
+	status = pj_sock_getsockname(sock, &addr, &addr_len);
+	if (status != PJ_SUCCESS)
 	    goto on_exit;
 	    
-        fe->cfg.port = pj_sockaddr_in_get_port(&addr);
-	if (param) 
-	    param->port = fe->cfg.port;
-	
-        PJ_LOG(3, (THIS_FILE, "CLI telnet daemon listening at port %d",
-		   fe->cfg.port));
-	
+        fe->cfg.port = pj_sockaddr_in_get_port(&addr);	
+
 	if (fe->cfg.prompt_str.slen == 0) {
 	    pj_str_t prompt_sign = {"> ", 2};
@@ -1738,33 +1809,49 @@
     }
 
-    sstatus = pj_sock_listen(sock, 4);
-    if (sstatus != PJ_SUCCESS)
+    status = pj_sock_listen(sock, 4);
+    if (status != PJ_SUCCESS)
         goto on_exit;
 
     pj_bzero(&asock_cb, sizeof(asock_cb));
-    asock_cb.on_accept_complete = &telnet_fe_on_accept;
-    sstatus = pj_activesock_create(pool, sock, pj_SOCK_STREAM(),
-                                   NULL, fe->cfg.ioqueue,
-		                   &asock_cb, fe, &fe->asock);
-    if (sstatus != PJ_SUCCESS)
+    asock_cb.on_accept_complete2 = &telnet_fe_on_accept;
+    status = pj_activesock_create(fe->pool, sock, pj_SOCK_STREAM(),
+                                  NULL, fe->cfg.ioqueue,
+		                  &asock_cb, fe, &fe->asock);
+    if (status != PJ_SUCCESS)
         goto on_exit;
 
-    sstatus = pj_activesock_start_accept(fe->asock, pool);
-    if (sstatus != PJ_SUCCESS)
+    status = pj_activesock_start_accept(fe->asock, fe->pool);
+    if (status != PJ_SUCCESS)
         goto on_exit;
 
     if (fe->own_ioqueue) {
         /* Create our own worker thread */
-        sstatus = pj_thread_create(pool, "worker_telnet_fe",
-                                   &poll_worker_thread, fe, 0, 0,
-                                   &fe->worker_thread);
-        if (sstatus != PJ_SUCCESS)
+        status = pj_thread_create(fe->pool, "worker_telnet_fe",
+                                  &poll_worker_thread, fe, 0, 0,
+                                  &fe->worker_thread);
+        if (status != PJ_SUCCESS)
             goto on_exit;
     }
 
-    pj_cli_register_front_end(cli, &fe->base);
-
-    if (p_fe)
-        *p_fe = &fe->base;
+    /** Fill telnet information and call pj_cli_telnet_on_started callback */
+    if (fe->cfg.on_started) {
+	char ip_addr[32];
+	pj_cli_telnet_info telnet_info;
+	pj_sockaddr hostip;
+
+	telnet_info.ip_address.ptr = ip_addr;
+	telnet_info.ip_address.slen = 0;
+	
+	status = pj_gethostip(pj_AF_INET(), &hostip);
+	if (status != PJ_SUCCESS)
+	    goto on_exit;
+
+	pj_strcpy2(&telnet_info.ip_address, 
+		   pj_inet_ntoa(hostip.ipv4.sin_addr));
+
+	telnet_info.port = fe->cfg.port;
+
+	(*fe->cfg.on_started)(&telnet_info);
+    }
 
     return PJ_SUCCESS;
@@ -1782,5 +1869,47 @@
         pj_mutex_destroy(fe->mutex);
 
-    pj_pool_release(pool);
-    return sstatus;
-}
+    pj_pool_release(fe->pool);
+    return status;
+}
+
+static pj_status_t telnet_restart(cli_telnet_fe *fe)
+{
+    pj_status_t status;
+    pj_cli_sess *sess;      
+
+    fe->is_quitting = PJ_TRUE;
+    if (fe->worker_thread) {	
+	pj_thread_join(fe->worker_thread);
+    }
+
+    pj_mutex_lock(fe->mutex);
+
+    /* Destroy all the sessions */
+    sess = fe->sess_head.next;
+    while (sess != &fe->sess_head) {
+	(*sess->op->destroy)(sess);
+	sess = fe->sess_head.next;
+    }
+
+    pj_mutex_unlock(fe->mutex);
+
+    /** Close existing activesock **/
+    status = pj_activesock_close(fe->asock);
+    if (status != PJ_SUCCESS)
+	goto on_exit;
+
+    if (fe->worker_thread) {
+	pj_thread_destroy(fe->worker_thread);
+	fe->worker_thread = NULL;
+    }
+
+    fe->is_quitting = PJ_FALSE;
+
+    /** Start Telnet **/
+    status = telnet_start(fe);
+    if (status == PJ_SUCCESS)
+	TRACE_((THIS_FILE, "Telnet Restarted"));
+    
+on_exit:
+    return status;
+}
Index: /pjproject/trunk/pjlib/include/pj/activesock.h
===================================================================
--- /pjproject/trunk/pjlib/include/pj/activesock.h	(revision 4460)
+++ /pjproject/trunk/pjlib/include/pj/activesock.h	(revision 4461)
@@ -133,5 +133,6 @@
     /**
      * This callback is called when new connection arrives as the result
-     * of pj_activesock_start_accept().
+     * of pj_activesock_start_accept(). If the status of accept operation is
+     * needed use on_accept_complete2 instead of this callback.
      *
      * @param asock	The active socket.
@@ -149,4 +150,28 @@
 				    const pj_sockaddr_t *src_addr,
 				    int src_addr_len);
+
+    /**
+     * This callback is called when new connection arrives as the result
+     * of pj_activesock_start_accept().
+     *
+     * @param asock	The active socket.
+     * @param newsock	The new incoming socket.
+     * @param src_addr	The source address of the connection.
+     * @param addr_len	Length of the source address.
+     * @param status	The status of the accept operation. This may contain
+     *			non-PJ_SUCCESS for example when the TCP listener is in
+     *			bad state for example on iOS platform after the
+     *			application waking up from background.
+     *
+     * @return		PJ_TRUE if further accept() is desired, and PJ_FALSE
+     *			when application no longer wants to accept incoming
+     *			connection. Application may destroy the active socket
+     *			in the callback and return PJ_FALSE here.
+     */
+    pj_bool_t (*on_accept_complete2)(pj_activesock_t *asock,
+				     pj_sock_t newsock,
+				     const pj_sockaddr_t *src_addr,
+				     int src_addr_len, 
+				     pj_status_t status);
 
     /**
Index: /pjproject/trunk/pjlib/include/pj/errno.h
===================================================================
--- /pjproject/trunk/pjlib/include/pj/errno.h	(revision 4460)
+++ /pjproject/trunk/pjlib/include/pj/errno.h	(revision 4461)
@@ -428,4 +428,9 @@
  */
 #define PJ_EGONE	    (PJ_ERRNO_START_STATUS + 23)/* 70023 */
+/**
+ * @hideinitializer
+ * Socket is stopped
+ */
+#define PJ_ESOCKETSTOP	    (PJ_ERRNO_START_STATUS + 24)/* 70024 */
 
 /** @} */   /* pj_errnum */
Index: /pjproject/trunk/pjlib/src/pj/activesock.c
===================================================================
--- /pjproject/trunk/pjlib/src/pj/activesock.c	(revision 4460)
+++ /pjproject/trunk/pjlib/src/pj/activesock.c	(revision 4461)
@@ -844,4 +844,14 @@
 			       " operation, stopping further ioqueue accepts.",
 			       asock->err_counter, asock->last_err));
+		
+		if ((status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) && 
+		    (asock->cb.on_accept_complete2)) 
+		{
+		    (*asock->cb.on_accept_complete2)(asock, 
+						     accept_op->new_sock,
+						     &accept_op->rem_addr,
+						     accept_op->rem_addr_len,
+						     PJ_ESOCKETSTOP);
+		}
 		return;
 	    }
@@ -851,11 +861,21 @@
 	}
 
-	if (status==PJ_SUCCESS && asock->cb.on_accept_complete) {
+	if (status==PJ_SUCCESS && (asock->cb.on_accept_complete2 || 
+				   asock->cb.on_accept_complete)) {
 	    pj_bool_t ret;
 
 	    /* Notify callback */
-	    ret = (*asock->cb.on_accept_complete)(asock, accept_op->new_sock,
-						  &accept_op->rem_addr,
-						  accept_op->rem_addr_len);
+	    if (asock->cb.on_accept_complete2) {
+		ret = (*asock->cb.on_accept_complete2)(asock, 
+						       accept_op->new_sock,
+						       &accept_op->rem_addr,
+						       accept_op->rem_addr_len,
+						       status);
+	    } else {
+		ret = (*asock->cb.on_accept_complete)(asock, 
+						      accept_op->new_sock,
+						      &accept_op->rem_addr,
+						      accept_op->rem_addr_len);	    
+	    }
 
 	    /* If callback returns false, we have been destroyed! */
Index: /pjproject/trunk/pjlib/src/pj/errno.c
===================================================================
--- /pjproject/trunk/pjlib/src/pj/errno.c	(revision 4460)
+++ /pjproject/trunk/pjlib/src/pj/errno.c	(revision 4461)
@@ -79,5 +79,6 @@
     PJ_BUILD_ERR(PJ_EIPV6NOTSUP,   "IPv6 is not supported"),
     PJ_BUILD_ERR(PJ_EAFNOTSUP,	   "Unsupported address family"),
-    PJ_BUILD_ERR(PJ_EGONE,	   "Object no longer exists")
+    PJ_BUILD_ERR(PJ_EGONE,	   "Object no longer exists"),
+    PJ_BUILD_ERR(PJ_ESOCKETSTOP,   "Socket is in bad state")
 };
 #endif	/* PJ_HAS_ERROR_STRING */
Index: /pjproject/trunk/pjsip-apps/build/Makefile
===================================================================
--- /pjproject/trunk/pjsip-apps/build/Makefile	(revision 4460)
+++ /pjproject/trunk/pjsip-apps/build/Makefile	(revision 4461)
@@ -34,5 +34,6 @@
 export PJSUA_SRCDIR = ../src/pjsua
 export PJSUA_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
-			main.o pjsua_app.o pjsua_cmd.o pjsua_cli_cmd.o pjsua_ui_cmd.o
+            main.o pjsua_app.o pjsua_cli.o pjsua_cli_cmd.o pjsua_common.o \
+            pjsua_config.o pjsua_legacy.o
 export PJSUA_CFLAGS += $(_CFLAGS)
 export PJSUA_LDFLAGS += $(APP_LDFLAGS) $(APP_LDLIBS) $(LDFLAGS)
Index: /pjproject/trunk/pjsip-apps/build/pjsua.vcproj
===================================================================
--- /pjproject/trunk/pjsip-apps/build/pjsua.vcproj	(revision 4460)
+++ /pjproject/trunk/pjsip-apps/build/pjsua.vcproj	(revision 4461)
@@ -3621,4 +3621,8 @@
 			</File>
 			<File
+				RelativePath="..\src\pjsua\pjsua_cli.c"
+				>
+			</File>
+			<File
 				RelativePath="..\src\pjsua\pjsua_cli_cmd.c"
 				>
@@ -4003,766 +4007,14 @@
 			</File>
 			<File
-				RelativePath="..\src\pjsua\pjsua_cmd.c"
+				RelativePath="..\src\pjsua\pjsua_common.c"
 				>
-				<FileConfiguration
-					Name="Release|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
 			</File>
 			<File
-				RelativePath="..\src\pjsua\pjsua_ui_cmd.c"
+				RelativePath="..\src\pjsua\pjsua_config.c"
 				>
-				<FileConfiguration
-					Name="Release|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Pocket PC 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Smartphone 2003 (ARMV4)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Static|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Dynamic|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug-Dynamic|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 6 Standard SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 6 Professional SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 5.0 Pocket PC SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release-Static|Windows Mobile 5.0 Smartphone SDK (ARMV4I)"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories=""
-						PreprocessorDefinitions=""
-					/>
-				</FileConfiguration>
+			</File>
+			<File
+				RelativePath="..\src\pjsua\pjsua_legacy.c"
+				>
 			</File>
 		</Filter>
@@ -4772,5 +4024,5 @@
 			>
 			<File
-				RelativePath="..\src\pjsua\pjsua_cmd.h"
+				RelativePath="..\src\pjsua\pjsua_common.h"
 				>
 			</File>
Index: /pjproject/trunk/pjsip-apps/src/pjsua/main.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/main.c	(revision 4460)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/main.c	(revision 4461)
@@ -27,89 +27,5 @@
  * These are defined in pjsua_app.c.
  */
-extern pj_bool_t app_restart;
-pj_status_t app_init(int argc, char *argv[]);
-pj_status_t app_main(void);
-pj_status_t app_destroy();
-pj_status_t receive_end_sig;
-pj_thread_t *sig_thread;
-
-#if defined(PJ_WIN32) && PJ_WIN32!=0
-#include <windows.h>
-
-static pj_thread_desc handler_desc;
-
-static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
-{   
-    switch (fdwCtrlType) 
-    { 
-        // Handle the CTRL+C signal. 
- 
-        case CTRL_C_EVENT: 
-        case CTRL_CLOSE_EVENT: 
-        case CTRL_BREAK_EVENT: 
-        case CTRL_LOGOFF_EVENT: 
-        case CTRL_SHUTDOWN_EVENT: 
-	    pj_thread_register("ctrlhandler", handler_desc, &sig_thread);
-	    PJ_LOG(3,(THIS_FILE, "Ctrl-C detected, quitting.."));
-	    receive_end_sig = PJ_TRUE;
-            app_destroy();	    
-	    ExitProcess(1);
-            PJ_UNREACHED(return TRUE;)
- 
-        default: 
- 
-            return FALSE; 
-    } 
-}
-
-static void setup_signal_handler(void)
-{
-    SetConsoleCtrlHandler(&CtrlHandler, TRUE);
-}
-
-static void setup_socket_signal()
-{
-}
-
-#else
-#include <signal.h>
-
-static void setup_signal_handler(void)
-{
-}
-
-static void setup_socket_signal()
-{
-    signal(SIGPIPE, SIG_IGN);
-}
-
-#endif
-
-static int main_func(int argc, char *argv[])
-{
-    receive_end_sig = PJ_FALSE;
-    setup_socket_signal();
-
-    do {
-	app_restart = PJ_FALSE;
-
-	if (app_init(argc, argv) != PJ_SUCCESS)
-	    return 1;
-
-	setup_signal_handler();
-
-	app_main();
-	if (!receive_end_sig) {
-	    app_destroy();
-
-	    /* This is on purpose */
-	    app_destroy();
-	} else {
-	    pj_thread_join(sig_thread);
-	}
-    } while (app_restart);
-
-    return 0;
-}
+int main_func(int argc, char *argv[]);
 
 int main(int argc, char *argv[])
Index: /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_app.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_app.c	(revision 4460)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_app.c	(revision 4461)
@@ -18,5 +18,5 @@
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
  */
-#include "pjsua_cmd.h"
+#include "pjsua_common.h"
 #include "gui.h"
 
@@ -44,6 +44,4 @@
 #define current_acc	pjsua_acc_get_default()
 
-static pj_str_t		uri_arg;
-
 #ifdef STEREO_DEMO
 static void stereo_demo();
@@ -51,19 +49,30 @@
 
 pj_status_t app_destroy(void);
+
 static void ringback_start(pjsua_call_id call_id);
 static void ring_start(pjsua_call_id call_id);
 static void ring_stop(pjsua_call_id call_id);
 
-pj_bool_t 	app_restart;
-pj_log_func     *log_cb = NULL;
-static const char      *stdout_refresh_text = "STDOUT_REFRESH";
+static pj_status_t	    receive_end_sig;
+static pj_thread_t	    *sig_thread;
+pj_str_t		    uri_arg;
+pj_bool_t 		    app_restart;
+pj_bool_t		    app_running	= PJ_FALSE;
+pj_log_func		    *log_cb = NULL;
 
 /** Forward declaration **/
-void console_app_main(const pj_str_t *uri_to_call, pj_bool_t *app_restart);
-
-void cli_console_app_main(const pj_str_t *uri_to_call, pj_bool_t *app_restart);
+/** Defined in pjsua_common.c **/
 void app_config_init_video(pjsua_acc_config *acc_cfg);
-pj_status_t setup_cli();
-void destroy_cli();
+/** Defined in pjsua_legacy.c **/
+void start_ui_main(pj_str_t *uri_to_call, pj_bool_t *app_restart);
+/** Defined in pjsua_cli.c **/
+void start_cli_main(pj_str_t *uri_to_call, pj_bool_t *app_restart);
+pj_status_t setup_cli(pj_bool_t with_console, pj_bool_t with_telnet,
+		      pj_uint16_t telnet_port, 
+		      pj_cli_telnet_on_started on_started_cb,
+		      pj_cli_on_quit on_quit_cb,
+		      pj_cli_on_destroy on_destroy_cb,
+		      pj_cli_on_restart_pjsua on_restart_pjsua_cb);
+void destroy_cli(pj_bool_t app_restart);
 
 /*****************************************************************************
@@ -92,1455 +101,6 @@
 #endif
 
-/* Show usage */
-static void usage(void)
-{
-    puts  ("Usage:");
-    puts  ("  pjsua [options] [SIP URL to call]");
-    puts  ("");
-    puts  ("General options:");
-    puts  ("  --config-file=file  Read the config/arguments from file.");
-    puts  ("  --help              Display this help screen");
-    puts  ("  --version           Display version info");
-    puts  ("");
-    puts  ("Logging options:");
-    puts  ("  --log-file=fname    Log to filename (default stderr)");
-    puts  ("  --log-level=N       Set log max level to N (0(none) to 6(trace)) (default=5)");
-    puts  ("  --app-log-level=N   Set log max level for stdout display (default=4)");
-    puts  ("  --log-append        Append instead of overwrite existing log file.\n");
-    puts  ("  --color             Use colorful logging (default yes on Win32)");
-    puts  ("  --no-color          Disable colorful logging");
-    puts  ("  --light-bg          Use dark colors for light background (default is dark bg)");
-    puts  ("  --no-stderr         Disable stderr");
-
-    puts  ("");
-    puts  ("SIP Account options:");
-    puts  ("  --registrar=url     Set the URL of registrar server");
-    puts  ("  --id=url            Set the URL of local ID (used in From header)");
-    puts  ("  --realm=string      Set realm");
-    puts  ("  --username=string   Set authentication username");
-    puts  ("  --password=string   Set authentication password");
-    puts  ("  --contact=url       Optionally override the Contact information");
-    puts  ("  --contact-params=S  Append the specified parameters S in Contact header");
-    puts  ("  --contact-uri-params=S  Append the specified parameters S in Contact URI");
-    puts  ("  --proxy=url         Optional URL of proxy server to visit");
-    puts  ("                      May be specified multiple times");
-    printf("  --reg-timeout=SEC   Optional registration interval (default %d)\n",
-	    PJSUA_REG_INTERVAL);
-    printf("  --rereg-delay=SEC   Optional auto retry registration interval (default %d)\n",
-	    PJSUA_REG_RETRY_INTERVAL);
-    puts  ("  --reg-use-proxy=N   Control the use of proxy settings in REGISTER.");
-    puts  ("                      0=no proxy, 1=outbound only, 2=acc only, 3=all (default)");
-    puts  ("  --publish           Send presence PUBLISH for this account");
-    puts  ("  --mwi               Subscribe to message summary/waiting indication");
-    puts  ("  --use-ims           Enable 3GPP/IMS related settings on this account");
-#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
-    puts  ("  --use-srtp=N        Use SRTP?  0:disabled, 1:optional, 2:mandatory,");
-    puts  ("                      3:optional by duplicating media offer (def:0)");
-    puts  ("  --srtp-secure=N     SRTP require secure SIP? 0:no, 1:tls, 2:sips (def:1)");
-#endif
-    puts  ("  --use-100rel        Require reliable provisional response (100rel)");
-    puts  ("  --use-timer=N       Use SIP session timers? (default=1)");
-    puts  ("                      0:inactive, 1:optional, 2:mandatory, 3:always");
-    printf("  --timer-se=N        Session timers expiration period, in secs (def:%d)\n",
-	    PJSIP_SESS_TIMER_DEF_SE);
-    puts  ("  --timer-min-se=N    Session timers minimum expiration period, in secs (def:90)");
-    puts  ("  --outb-rid=string   Set SIP outbound reg-id (default:1)");
-    puts  ("  --auto-update-nat=N Where N is 0 or 1 to enable/disable SIP traversal behind");
-    puts  ("                      symmetric NAT (default 1)");
-    puts  ("  --disable-stun      Disable STUN for this account");
-    puts  ("  --next-cred         Add another credentials");
-    puts  ("");
-    puts  ("SIP Account Control:");
-    puts  ("  --next-account      Add more account");
-    puts  ("");
-    puts  ("Transport Options:");
-#if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6
-    puts  ("  --ipv6              Use IPv6 instead for SIP and media.");
-#endif
-    puts  ("  --set-qos           Enable QoS tagging for SIP and media.");
-    puts  ("  --local-port=port   Set TCP/UDP port. This implicitly enables both ");
-    puts  ("                      TCP and UDP transports on the specified port, unless");
-    puts  ("                      if TCP or UDP is disabled.");
-    puts  ("  --ip-addr=IP        Use the specifed address as SIP and RTP addresses.");
-    puts  ("                      (Hint: the IP may be the public IP of the NAT/router)");
-    puts  ("  --bound-addr=IP     Bind transports to this IP interface");
-    puts  ("  --no-tcp            Disable TCP transport.");
-    puts  ("  --no-udp            Disable UDP transport.");
-    puts  ("  --nameserver=NS     Add the specified nameserver to enable SRV resolution");
-    puts  ("                      This option can be specified multiple times.");
-    puts  ("  --outbound=url      Set the URL of global outbound proxy server");
-    puts  ("                      May be specified multiple times");
-    puts  ("  --stun-srv=FORMAT   Set STUN server host or domain. This option may be");
-    puts  ("                      specified more than once. FORMAT is hostdom[:PORT]");
-
-#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
-    puts  ("");
-    puts  ("TLS Options:");
-    puts  ("  --use-tls           Enable TLS transport (default=no)");
-    puts  ("  --tls-ca-file       Specify TLS CA file (default=none)");
-    puts  ("  --tls-cert-file     Specify TLS certificate file (default=none)");
-    puts  ("  --tls-privkey-file  Specify TLS private key file (default=none)");
-    puts  ("  --tls-password      Specify TLS password to private key file (default=none)");
-    puts  ("  --tls-verify-server Verify server's certificate (default=no)");
-    puts  ("  --tls-verify-client Verify client's certificate (default=no)");
-    puts  ("  --tls-neg-timeout   Specify TLS negotiation timeout (default=no)");
-    puts  ("  --tls-srv-name      Specify TLS server name for multihosting server");
-    puts  ("  --tls-cipher        Specify prefered TLS cipher (optional).");
-    puts  ("                      May be specified multiple times");
-#endif
-
-    puts  ("");
-    puts  ("Audio Options:");
-    puts  ("  --add-codec=name    Manually add codec (default is to enable all)");
-    puts  ("  --dis-codec=name    Disable codec (can be specified multiple times)");
-    puts  ("  --clock-rate=N      Override conference bridge clock rate");
-    puts  ("  --snd-clock-rate=N  Override sound device clock rate");
-    puts  ("  --stereo            Audio device and conference bridge opened in stereo mode");
-    puts  ("  --null-audio        Use NULL audio device");
-    puts  ("  --play-file=file    Register WAV file in conference bridge.");
-    puts  ("                      This can be specified multiple times.");
-    puts  ("  --play-tone=FORMAT  Register tone to the conference bridge.");
-    puts  ("                      FORMAT is 'F1,F2,ON,OFF', where F1,F2 are");
-    puts  ("                      frequencies, and ON,OFF=on/off duration in msec.");
-    puts  ("                      This can be specified multiple times.");
-    puts  ("  --auto-play         Automatically play the file (to incoming calls only)");
-    puts  ("  --auto-loop         Automatically loop incoming RTP to outgoing RTP");
-    puts  ("  --auto-conf         Automatically put calls in conference with others");
-    puts  ("  --rec-file=file     Open file recorder (extension can be .wav or .mp3");
-    puts  ("  --auto-rec          Automatically record conversation");
-    puts  ("  --quality=N         Specify media quality (0-10, default=6)");
-    puts  ("  --ptime=MSEC        Override codec ptime to MSEC (default=specific)");
-    puts  ("  --no-vad            Disable VAD/silence detector (default=vad enabled)");
-    puts  ("  --ec-tail=MSEC      Set echo canceller tail length (default=256)");
-    puts  ("  --ec-opt=OPT        Select echo canceller algorithm (0=default, ");
-    puts  ("                        1=speex, 2=suppressor)");
-    puts  ("  --ilbc-mode=MODE    Set iLBC codec mode (20 or 30, default is 30)");
-    puts  ("  --capture-dev=id    Audio capture device ID (default=-1)");
-    puts  ("  --playback-dev=id   Audio playback device ID (default=-1)");
-    puts  ("  --capture-lat=N     Audio capture latency, in ms (default=100)");
-    puts  ("  --playback-lat=N    Audio playback latency, in ms (default=100)");
-    puts  ("  --snd-auto-close=N  Auto close audio device when idle for N secs (default=1)");
-    puts  ("                      Specify N=-1 to disable this feature.");
-    puts  ("                      Specify N=0 for instant close when unused.");
-    puts  ("  --no-tones          Disable audible tones");
-    puts  ("  --jb-max-size       Specify jitter buffer maximum size, in frames (default=-1)");
-    puts  ("  --extra-audio       Add one more audio stream");
-
-#if PJSUA_HAS_VIDEO
-    puts  ("");
-    puts  ("Video Options:");
-    puts  ("  --video             Enable video");
-    puts  ("  --vcapture-dev=id   Video capture device ID (default=-1)");
-    puts  ("  --vrender-dev=id    Video render device ID (default=-2)");
-    puts  ("  --play-avi=FILE     Load this AVI as virtual capture device");
-    puts  ("  --auto-play-avi     Automatically play the AVI media to call");
-#endif
-
-    puts  ("");
-    puts  ("Media Transport Options:");
-    puts  ("  --use-ice           Enable ICE (default:no)");
-    puts  ("  --ice-regular       Use ICE regular nomination (default: aggressive)");
-    puts  ("  --ice-max-hosts=N   Set maximum number of ICE host candidates");
-    puts  ("  --ice-no-rtcp       Disable RTCP component in ICE (default: no)");
-    puts  ("  --rtp-port=N        Base port to try for RTP (default=4000)");
-    puts  ("  --rx-drop-pct=PCT   Drop PCT percent of RX RTP (for pkt lost sim, default: 0)");
-    puts  ("  --tx-drop-pct=PCT   Drop PCT percent of TX RTP (for pkt lost sim, default: 0)");
-    puts  ("  --use-turn          Enable TURN relay with ICE (default:no)");
-    puts  ("  --turn-srv          Domain or host name of TURN server (\"NAME:PORT\" format)");
-    puts  ("  --turn-tcp          Use TCP connection to TURN server (default no)");
-    puts  ("  --turn-user         TURN username");
-    puts  ("  --turn-passwd       TURN password");
-
-    puts  ("");
-    puts  ("Buddy List (can be more than one):");
-    puts  ("  --add-buddy url     Add the specified URL to the buddy list.");
-    puts  ("");
-    puts  ("User Agent options:");
-    puts  ("  --auto-answer=code  Automatically answer incoming calls with code (e.g. 200)");
-    puts  ("  --max-calls=N       Maximum number of concurrent calls (default:4, max:255)");
-    puts  ("  --thread-cnt=N      Number of worker threads (default:1)");
-    puts  ("  --duration=SEC      Set maximum call duration (default:no limit)");
-    puts  ("  --norefersub        Suppress event subscription when transfering calls");
-    puts  ("  --use-compact-form  Minimize SIP message size");
-    puts  ("  --no-force-lr       Allow strict-route to be used (i.e. do not force lr)");
-    puts  ("  --accept-redirect=N Specify how to handle call redirect (3xx) response.");
-    puts  ("                      0: reject, 1: follow automatically,");
-    puts  ("                      2: follow + replace To header (default), 3: ask");
-
-    puts  ("");
-    puts  ("CLI options:");
-    puts  ("  --use-cli           Use CLI as user interface");
-    puts  ("  --cli-telnet-port=N CLI telnet port");
-    puts  ("");
-
-    puts  ("");
-    puts  ("When URL is specified, pjsua will immediately initiate call to that URL");
-    puts  ("");
-
-    fflush(stdout);
-}
-
-static int stdout_refresh_proc(void *arg)
-{
-    PJ_UNUSED_ARG(arg);
-
-    /* Set thread to lowest priority so that it doesn't clobber
-     * stdout output
-     */
-    pj_thread_set_prio(pj_thread_this(), 
-		       pj_thread_get_prio_min(pj_thread_this()));
-
-    while (!stdout_refresh_quit) {
-	pj_thread_sleep(stdout_refresh * 1000);
-	puts(stdout_refresh_text);
-	fflush(stdout);
-    }
-
-    return 0;
-}
-
-/* Set default config. */
-static void default_config(pjsua_app_config *cfg)
-{
-    char tmp[80];
-    unsigned i;
-
-    pjsua_config_default(&cfg->cfg);
-    pj_ansi_sprintf(tmp, "PJSUA v%s %s", pj_get_version(),
-		    pj_get_sys_info()->info.ptr);
-    pj_strdup2_with_null(app_config.pool, &cfg->cfg.user_agent, tmp);
-
-    pjsua_logging_config_default(&cfg->log_cfg);
-    pjsua_media_config_default(&cfg->media_cfg);
-    pjsua_transport_config_default(&cfg->udp_cfg);
-    cfg->udp_cfg.port = 5060;
-    pjsua_transport_config_default(&cfg->rtp_cfg);
-    cfg->rtp_cfg.port = 4000;
-    cfg->redir_op = PJSIP_REDIRECT_ACCEPT_REPLACE;
-    cfg->duration = NO_LIMIT_DURATION;
-    cfg->wav_id = PJSUA_INVALID_ID;
-    cfg->rec_id = PJSUA_INVALID_ID;
-    cfg->wav_port = PJSUA_INVALID_ID;
-    cfg->rec_port = PJSUA_INVALID_ID;
-    cfg->mic_level = cfg->speaker_level = 1.0;
-    cfg->capture_dev = PJSUA_INVALID_ID;
-    cfg->playback_dev = PJSUA_INVALID_ID;
-    cfg->capture_lat = PJMEDIA_SND_DEFAULT_REC_LATENCY;
-    cfg->playback_lat = PJMEDIA_SND_DEFAULT_PLAY_LATENCY;
-    cfg->ringback_slot = PJSUA_INVALID_ID;
-    cfg->ring_slot = PJSUA_INVALID_ID;
-
-    for (i=0; i<PJ_ARRAY_SIZE(cfg->acc_cfg); ++i)
-	pjsua_acc_config_default(&cfg->acc_cfg[i]);
-
-    for (i=0; i<PJ_ARRAY_SIZE(cfg->buddy_cfg); ++i)
-	pjsua_buddy_config_default(&cfg->buddy_cfg[i]);
-
-    cfg->vid.vcapture_dev = PJMEDIA_VID_DEFAULT_CAPTURE_DEV;
-    cfg->vid.vrender_dev = PJMEDIA_VID_DEFAULT_RENDER_DEV;
-    cfg->aud_cnt = 1;
-
-    cfg->avi_def_idx = PJSUA_INVALID_ID;
-
-    cfg->use_cli = PJ_FALSE;
-    cfg->cli_telnet_port = 0;
-}
-
-/*
- * Read command arguments from config file.
- */
-static int read_config_file(pj_pool_t *pool, const char *filename, 
-			    int *app_argc, char ***app_argv)
-{
-    int i;
-    FILE *fhnd;
-    char line[200];
-    int argc = 0;
-    char **argv;
-    enum { MAX_ARGS = 128 };
-
-    /* Allocate MAX_ARGS+1 (argv needs to be terminated with NULL argument) */
-    argv = pj_pool_calloc(pool, MAX_ARGS+1, sizeof(char*));
-    argv[argc++] = *app_argv[0];
-
-    /* Open config file. */
-    fhnd = fopen(filename, "rt");
-    if (!fhnd) {
-	PJ_LOG(1,(THIS_FILE, "Unable to open config file %s", filename));
-	fflush(stdout);
-	return -1;
-    }
-
-    /* Scan tokens in the file. */
-    while (argc < MAX_ARGS && !feof(fhnd)) {
-	char  *token;
-	char  *p;
-	const char *whitespace = " \t\r\n";
-	char  cDelimiter;
-	int   len, token_len;
-	
-	pj_bzero(line, sizeof(line));
-	if (fgets(line, sizeof(line), fhnd) == NULL) break;
-	
-	// Trim ending newlines
-	len = strlen(line);
-	if (line[len-1]=='\n')
-	    line[--len] = '\0';
-	if (line[len-1]=='\r')
-	    line[--len] = '\0';
-
-	if (len==0) continue;
-
-	for (p = line; *p != '\0' && argc < MAX_ARGS; p++) {
-	    // first, scan whitespaces
-	    while (*p != '\0' && strchr(whitespace, *p) != NULL) p++;
-
-	    if (*p == '\0')		    // are we done yet?
-		break;
-	    
-	    if (*p == '"' || *p == '\'') {    // is token a quoted string
-		cDelimiter = *p++;	    // save quote delimiter
-		token = p;
-		
-		while (*p != '\0' && *p != cDelimiter) p++;
-		
-		if (*p == '\0')		// found end of the line, but,
-		    cDelimiter = '\0';	// didn't find a matching quote
-
-	    } else {			// token's not a quoted string
-		token = p;
-		
-		while (*p != '\0' && strchr(whitespace, *p) == NULL) p++;
-		
-		cDelimiter = *p;
-	    }
-	    
-	    *p = '\0';
-	    token_len = p-token;
-	    
-	    if (token_len > 0) {
-		if (*token == '#')
-		    break;  // ignore remainder of line
-		
-		argv[argc] = pj_pool_alloc(pool, token_len + 1);
-		pj_memcpy(argv[argc], token, token_len + 1);
-		++argc;
-	    }
-	    
-	    *p = cDelimiter;
-	}
-    }
-
-    /* Copy arguments from command line */
-    for (i=1; i<*app_argc && argc < MAX_ARGS; ++i)
-	argv[argc++] = (*app_argv)[i];
-
-    if (argc == MAX_ARGS && (i!=*app_argc || !feof(fhnd))) {
-	PJ_LOG(1,(THIS_FILE, 
-		  "Too many arguments specified in cmd line/config file"));
-	fflush(stdout);
-	fclose(fhnd);
-	return -1;
-    }
-
-    fclose(fhnd);
-
-    /* Assign the new command line back to the original command line. */
-    *app_argc = argc;
-    *app_argv = argv;
-    return 0;
-}
-
-/* Parse arguments. */
-static pj_status_t parse_args(int argc, char *argv[], 
-			      pjsua_app_config *cfg,
-			      pj_str_t *uri_to_call)
-{
-    int c;
-    int option_index;
-    enum { OPT_CONFIG_FILE=127, OPT_LOG_FILE, OPT_LOG_LEVEL, OPT_APP_LOG_LEVEL, 
-	   OPT_LOG_APPEND, OPT_COLOR, OPT_NO_COLOR, OPT_LIGHT_BG, OPT_NO_STDERR,
-	   OPT_HELP, OPT_VERSION, OPT_NULL_AUDIO, OPT_SND_AUTO_CLOSE,
-	   OPT_LOCAL_PORT, OPT_IP_ADDR, OPT_PROXY, OPT_OUTBOUND_PROXY, 
-	   OPT_REGISTRAR, OPT_REG_TIMEOUT, OPT_PUBLISH, OPT_ID, OPT_CONTACT,
-	   OPT_BOUND_ADDR, OPT_CONTACT_PARAMS, OPT_CONTACT_URI_PARAMS,
-	   OPT_100REL, OPT_USE_IMS, OPT_REALM, OPT_USERNAME, OPT_PASSWORD,
-	   OPT_REG_RETRY_INTERVAL, OPT_REG_USE_PROXY,
-	   OPT_MWI, OPT_NAMESERVER, OPT_STUN_SRV, OPT_OUTB_RID,
-	   OPT_ADD_BUDDY, OPT_OFFER_X_MS_MSG, OPT_NO_PRESENCE,
-	   OPT_AUTO_ANSWER, OPT_AUTO_PLAY, OPT_AUTO_PLAY_HANGUP, OPT_AUTO_LOOP,
-	   OPT_AUTO_CONF, OPT_CLOCK_RATE, OPT_SND_CLOCK_RATE, OPT_STEREO,
-	   OPT_USE_ICE, OPT_ICE_REGULAR, OPT_USE_SRTP, OPT_SRTP_SECURE,
-	   OPT_USE_TURN, OPT_ICE_MAX_HOSTS, OPT_ICE_NO_RTCP, OPT_TURN_SRV, 
-	   OPT_TURN_TCP, OPT_TURN_USER, OPT_TURN_PASSWD,
-	   OPT_PLAY_FILE, OPT_PLAY_TONE, OPT_RTP_PORT, OPT_ADD_CODEC, 
-	   OPT_ILBC_MODE, OPT_REC_FILE, OPT_AUTO_REC,
-	   OPT_COMPLEXITY, OPT_QUALITY, OPT_PTIME, OPT_NO_VAD,
-	   OPT_RX_DROP_PCT, OPT_TX_DROP_PCT, OPT_EC_TAIL, OPT_EC_OPT,
-	   OPT_NEXT_ACCOUNT, OPT_NEXT_CRED, OPT_MAX_CALLS, 
-	   OPT_DURATION, OPT_NO_TCP, OPT_NO_UDP, OPT_THREAD_CNT,
-	   OPT_NOREFERSUB, OPT_ACCEPT_REDIRECT,
-	   OPT_USE_TLS, OPT_TLS_CA_FILE, OPT_TLS_CERT_FILE, OPT_TLS_PRIV_FILE,
-	   OPT_TLS_PASSWORD, OPT_TLS_VERIFY_SERVER, OPT_TLS_VERIFY_CLIENT,
-	   OPT_TLS_NEG_TIMEOUT, OPT_TLS_CIPHER,
-	   OPT_CAPTURE_DEV, OPT_PLAYBACK_DEV,
-	   OPT_CAPTURE_LAT, OPT_PLAYBACK_LAT, OPT_NO_TONES, OPT_JB_MAX_SIZE,
-	   OPT_STDOUT_REFRESH, OPT_STDOUT_REFRESH_TEXT, OPT_IPV6, OPT_QOS,
-#ifdef _IONBF
-	   OPT_STDOUT_NO_BUF,
-#endif
-	   OPT_AUTO_UPDATE_NAT,OPT_USE_COMPACT_FORM,OPT_DIS_CODEC,
-	   OPT_DISABLE_STUN, OPT_NO_FORCE_LR,
-	   OPT_TIMER, OPT_TIMER_SE, OPT_TIMER_MIN_SE,
-	   OPT_VIDEO, OPT_EXTRA_AUDIO,
-	   OPT_VCAPTURE_DEV, OPT_VRENDER_DEV, OPT_PLAY_AVI, OPT_AUTO_PLAY_AVI,
-	   OPT_USE_CLI, OPT_CLI_TELNET_PORT
-    };
-    struct pj_getopt_option long_options[] = {
-	{ "config-file",1, 0, OPT_CONFIG_FILE},
-	{ "log-file",	1, 0, OPT_LOG_FILE},
-	{ "log-level",	1, 0, OPT_LOG_LEVEL},
-	{ "app-log-level",1,0,OPT_APP_LOG_LEVEL},
-	{ "log-append", 0, 0, OPT_LOG_APPEND},
-	{ "color",	0, 0, OPT_COLOR},
-	{ "no-color",	0, 0, OPT_NO_COLOR},
-	{ "light-bg",		0, 0, OPT_LIGHT_BG},
-	{ "no-stderr",  0, 0, OPT_NO_STDERR},
-	{ "help",	0, 0, OPT_HELP},
-	{ "version",	0, 0, OPT_VERSION},
-	{ "clock-rate",	1, 0, OPT_CLOCK_RATE},
-	{ "snd-clock-rate",	1, 0, OPT_SND_CLOCK_RATE},
-	{ "stereo",	0, 0, OPT_STEREO},
-	{ "null-audio", 0, 0, OPT_NULL_AUDIO},
-	{ "local-port", 1, 0, OPT_LOCAL_PORT},
-	{ "ip-addr",	1, 0, OPT_IP_ADDR},
-	{ "bound-addr", 1, 0, OPT_BOUND_ADDR},
-	{ "no-tcp",     0, 0, OPT_NO_TCP},
-	{ "no-udp",     0, 0, OPT_NO_UDP},
-	{ "norefersub", 0, 0, OPT_NOREFERSUB},
-	{ "proxy",	1, 0, OPT_PROXY},
-	{ "outbound",	1, 0, OPT_OUTBOUND_PROXY},
-	{ "registrar",	1, 0, OPT_REGISTRAR},
-	{ "reg-timeout",1, 0, OPT_REG_TIMEOUT},
-	{ "publish",    0, 0, OPT_PUBLISH},
-	{ "mwi",	0, 0, OPT_MWI},
-	{ "use-100rel", 0, 0, OPT_100REL},
-	{ "use-ims",    0, 0, OPT_USE_IMS},
-	{ "id",		1, 0, OPT_ID},
-	{ "contact",	1, 0, OPT_CONTACT},
-	{ "contact-params",1,0, OPT_CONTACT_PARAMS},
-	{ "contact-uri-params",1,0, OPT_CONTACT_URI_PARAMS},
-	{ "auto-update-nat",	1, 0, OPT_AUTO_UPDATE_NAT},
-	{ "disable-stun",0,0, OPT_DISABLE_STUN},
-        { "use-compact-form",	0, 0, OPT_USE_COMPACT_FORM},
-	{ "accept-redirect", 1, 0, OPT_ACCEPT_REDIRECT},
-	{ "no-force-lr",0, 0, OPT_NO_FORCE_LR},
-	{ "realm",	1, 0, OPT_REALM},
-	{ "username",	1, 0, OPT_USERNAME},
-	{ "password",	1, 0, OPT_PASSWORD},
-	{ "rereg-delay",1, 0, OPT_REG_RETRY_INTERVAL},
-	{ "reg-use-proxy", 1, 0, OPT_REG_USE_PROXY},
-	{ "nameserver", 1, 0, OPT_NAMESERVER},
-	{ "stun-srv",   1, 0, OPT_STUN_SRV},
-	{ "add-buddy",  1, 0, OPT_ADD_BUDDY},
-	{ "offer-x-ms-msg",0,0,OPT_OFFER_X_MS_MSG},
-	{ "no-presence", 0, 0, OPT_NO_PRESENCE},
-	{ "auto-answer",1, 0, OPT_AUTO_ANSWER},
-	{ "auto-play",  0, 0, OPT_AUTO_PLAY},
-	{ "auto-play-hangup",0, 0, OPT_AUTO_PLAY_HANGUP},
-	{ "auto-rec",   0, 0, OPT_AUTO_REC},
-	{ "auto-loop",  0, 0, OPT_AUTO_LOOP},
-	{ "auto-conf",  0, 0, OPT_AUTO_CONF},
-	{ "play-file",  1, 0, OPT_PLAY_FILE},
-	{ "play-tone",  1, 0, OPT_PLAY_TONE},
-	{ "rec-file",   1, 0, OPT_REC_FILE},
-	{ "rtp-port",	1, 0, OPT_RTP_PORT},
-
-	{ "use-ice",    0, 0, OPT_USE_ICE},
-	{ "ice-regular",0, 0, OPT_ICE_REGULAR},
-	{ "use-turn",	0, 0, OPT_USE_TURN},
-	{ "ice-max-hosts",1, 0, OPT_ICE_MAX_HOSTS},
-	{ "ice-no-rtcp",0, 0, OPT_ICE_NO_RTCP},
-	{ "turn-srv",	1, 0, OPT_TURN_SRV},
-	{ "turn-tcp",	0, 0, OPT_TURN_TCP},
-	{ "turn-user",	1, 0, OPT_TURN_USER},
-	{ "turn-passwd",1, 0, OPT_TURN_PASSWD},
-
-#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
-	{ "use-srtp",   1, 0, OPT_USE_SRTP},
-	{ "srtp-secure",1, 0, OPT_SRTP_SECURE},
-#endif
-	{ "add-codec",  1, 0, OPT_ADD_CODEC},
-	{ "dis-codec",  1, 0, OPT_DIS_CODEC},
-	{ "complexity",	1, 0, OPT_COMPLEXITY},
-	{ "quality",	1, 0, OPT_QUALITY},
-	{ "ptime",      1, 0, OPT_PTIME},
-	{ "no-vad",     0, 0, OPT_NO_VAD},
-	{ "ec-tail",    1, 0, OPT_EC_TAIL},
-	{ "ec-opt",	1, 0, OPT_EC_OPT},
-	{ "ilbc-mode",	1, 0, OPT_ILBC_MODE},
-	{ "rx-drop-pct",1, 0, OPT_RX_DROP_PCT},
-	{ "tx-drop-pct",1, 0, OPT_TX_DROP_PCT},
-	{ "next-account",0,0, OPT_NEXT_ACCOUNT},
-	{ "next-cred",	0, 0, OPT_NEXT_CRED},
-	{ "max-calls",	1, 0, OPT_MAX_CALLS},
-	{ "duration",	1, 0, OPT_DURATION},
-	{ "thread-cnt",	1, 0, OPT_THREAD_CNT},
-#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
-	{ "use-tls",	0, 0, OPT_USE_TLS}, 
-	{ "tls-ca-file",1, 0, OPT_TLS_CA_FILE},
-	{ "tls-cert-file",1,0, OPT_TLS_CERT_FILE}, 
-	{ "tls-privkey-file",1,0, OPT_TLS_PRIV_FILE},
-	{ "tls-password",1,0, OPT_TLS_PASSWORD},
-	{ "tls-verify-server", 0, 0, OPT_TLS_VERIFY_SERVER},
-	{ "tls-verify-client", 0, 0, OPT_TLS_VERIFY_CLIENT},
-	{ "tls-neg-timeout", 1, 0, OPT_TLS_NEG_TIMEOUT},
-	{ "tls-cipher", 1, 0, OPT_TLS_CIPHER},
-#endif
-	{ "capture-dev",    1, 0, OPT_CAPTURE_DEV},
-	{ "playback-dev",   1, 0, OPT_PLAYBACK_DEV},
-	{ "capture-lat",    1, 0, OPT_CAPTURE_LAT},
-	{ "playback-lat",   1, 0, OPT_PLAYBACK_LAT},
-	{ "stdout-refresh", 1, 0, OPT_STDOUT_REFRESH},
-	{ "stdout-refresh-text", 1, 0, OPT_STDOUT_REFRESH_TEXT},
-#ifdef _IONBF
-	{ "stdout-no-buf",  0, 0, OPT_STDOUT_NO_BUF },
-#endif
-	{ "snd-auto-close", 1, 0, OPT_SND_AUTO_CLOSE},
-	{ "no-tones",    0, 0, OPT_NO_TONES},
-	{ "jb-max-size", 1, 0, OPT_JB_MAX_SIZE},
-#if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6
-	{ "ipv6",	 0, 0, OPT_IPV6},
-#endif
-	{ "set-qos",	 0, 0, OPT_QOS},
-	{ "use-timer",  1, 0, OPT_TIMER},
-	{ "timer-se",   1, 0, OPT_TIMER_SE},
-	{ "timer-min-se", 1, 0, OPT_TIMER_MIN_SE},
-	{ "outb-rid",	1, 0, OPT_OUTB_RID},
-	{ "video",	0, 0, OPT_VIDEO},
-	{ "extra-audio",0, 0, OPT_EXTRA_AUDIO},
-	{ "vcapture-dev", 1, 0, OPT_VCAPTURE_DEV},
-	{ "vrender-dev",  1, 0, OPT_VRENDER_DEV},
-	{ "play-avi",	1, 0, OPT_PLAY_AVI},
-	{ "auto-play-avi", 0, 0, OPT_AUTO_PLAY_AVI},
-	{ "use-cli",	0, 0, OPT_USE_CLI},
-	{ "cli-telnet-port", 1, 0, OPT_CLI_TELNET_PORT},
-	{ NULL, 0, 0, 0}
-    };
-    pj_status_t status;
-    pjsua_acc_config *cur_acc;
-    char *config_file = NULL;
-    unsigned i;
-
-    /* Run pj_getopt once to see if user specifies config file to read. */ 
-    pj_optind = 0;
-    while ((c=pj_getopt_long(argc, argv, "", long_options, 
-			     &option_index)) != -1) 
-    {
-	switch (c) {
-	case OPT_CONFIG_FILE:
-	    config_file = pj_optarg;
-	    break;
-	}
-	if (config_file)
-	    break;
-    }
-
-    if (config_file) {
-	status = read_config_file(cfg->pool, config_file, &argc, &argv);
-	if (status != 0)
-	    return status;
-    }
-
-    cfg->acc_cnt = 0;
-    cur_acc = &cfg->acc_cfg[0];
-
-
-    /* Reinitialize and re-run pj_getopt again, possibly with new arguments
-     * read from config file.
-     */
-    pj_optind = 0;
-    while((c=pj_getopt_long(argc,argv, "", long_options,&option_index))!=-1) {
-	pj_str_t tmp;
-	long lval;
-
-	switch (c) {
-
-	case OPT_CONFIG_FILE:
-	    /* Ignore as this has been processed before */
-	    break;
-	
-	case OPT_LOG_FILE:
-	    cfg->log_cfg.log_filename = pj_str(pj_optarg);
-	    break;
-
-	case OPT_LOG_LEVEL:
-	    c = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (c < 0 || c > 6) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: expecting integer value 0-6 "
-			  "for --log-level"));
-		return PJ_EINVAL;
-	    }
-	    cfg->log_cfg.level = c;
-	    pj_log_set_level( c );
-	    break;
-
-	case OPT_APP_LOG_LEVEL:
-	    cfg->log_cfg.console_level = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (cfg->log_cfg.console_level < 0 || cfg->log_cfg.console_level > 6) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: expecting integer value 0-6 "
-			  "for --app-log-level"));
-		return PJ_EINVAL;
-	    }
-	    break;
-
-	case OPT_LOG_APPEND:
-	    cfg->log_cfg.log_file_flags |= PJ_O_APPEND;
-	    break;
-
-	case OPT_COLOR:
-	    cfg->log_cfg.decor |= PJ_LOG_HAS_COLOR;
-	    break;
-
-	case OPT_NO_COLOR:
-	    cfg->log_cfg.decor &= ~PJ_LOG_HAS_COLOR;
-	    break;
-
-	case OPT_LIGHT_BG:
-	    pj_log_set_color(1, PJ_TERM_COLOR_R);
-	    pj_log_set_color(2, PJ_TERM_COLOR_R | PJ_TERM_COLOR_G);
-	    pj_log_set_color(3, PJ_TERM_COLOR_B | PJ_TERM_COLOR_G);
-	    pj_log_set_color(4, 0);
-	    pj_log_set_color(5, 0);
-	    pj_log_set_color(77, 0);
-	    break;
-
-	case OPT_NO_STDERR:
-	    freopen("/dev/null", "w", stderr);
-	    break;
-
-	case OPT_HELP:
-	    usage();
-	    return PJ_EINVAL;
-
-	case OPT_VERSION:   /* version */
-	    pj_dump_config();
-	    return PJ_EINVAL;
-
-	case OPT_NULL_AUDIO:
-	    cfg->null_audio = PJ_TRUE;
-	    break;
-
-	case OPT_CLOCK_RATE:
-	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (lval < 8000 || lval > 192000) {
-		PJ_LOG(1,(THIS_FILE, "Error: expecting value between "
-				     "8000-192000 for conference clock rate"));
-		return PJ_EINVAL;
-	    }
-	    cfg->media_cfg.clock_rate = lval; 
-	    break;
-
-	case OPT_SND_CLOCK_RATE:
-	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (lval < 8000 || lval > 192000) {
-		PJ_LOG(1,(THIS_FILE, "Error: expecting value between "
-				     "8000-192000 for sound device clock rate"));
-		return PJ_EINVAL;
-	    }
-	    cfg->media_cfg.snd_clock_rate = lval; 
-	    break;
-
-	case OPT_STEREO:
-	    cfg->media_cfg.channel_count = 2;
-	    break;
-
-	case OPT_LOCAL_PORT:   /* local-port */
-	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (lval < 0 || lval > 65535) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: expecting integer value for "
-			  "--local-port"));
-		return PJ_EINVAL;
-	    }
-	    cfg->udp_cfg.port = (pj_uint16_t)lval;
-	    break;
-
-	case OPT_IP_ADDR: /* ip-addr */
-	    cfg->udp_cfg.public_addr = pj_str(pj_optarg);
-	    cfg->rtp_cfg.public_addr = pj_str(pj_optarg);
-	    break;
-
-	case OPT_BOUND_ADDR: /* bound-addr */
-	    cfg->udp_cfg.bound_addr = pj_str(pj_optarg);
-	    cfg->rtp_cfg.bound_addr = pj_str(pj_optarg);
-	    break;
-
-	case OPT_NO_UDP: /* no-udp */
-	    if (cfg->no_tcp && !cfg->use_tls) {
-	      PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP"));
-	      return PJ_EINVAL;
-	    }
-
-	    cfg->no_udp = PJ_TRUE;
-	    break;
-
-	case OPT_NOREFERSUB: /* norefersub */
-	    cfg->no_refersub = PJ_TRUE;
-	    break;
-
-	case OPT_NO_TCP: /* no-tcp */
-	    if (cfg->no_udp && !cfg->use_tls) {
-	      PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP"));
-	      return PJ_EINVAL;
-	    }
-
-	    cfg->no_tcp = PJ_TRUE;
-	    break;
-
-	case OPT_PROXY:   /* proxy */
-	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid SIP URL '%s' "
-			  "in proxy argument", pj_optarg));
-		return PJ_EINVAL;
-	    }
-	    cur_acc->proxy[cur_acc->proxy_cnt++] = pj_str(pj_optarg);
-	    break;
-
-	case OPT_OUTBOUND_PROXY:   /* outbound proxy */
-	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid SIP URL '%s' "
-			  "in outbound proxy argument", pj_optarg));
-		return PJ_EINVAL;
-	    }
-	    cfg->cfg.outbound_proxy[cfg->cfg.outbound_proxy_cnt++] = pj_str(pj_optarg);
-	    break;
-
-	case OPT_REGISTRAR:   /* registrar */
-	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid SIP URL '%s' in "
-			  "registrar argument", pj_optarg));
-		return PJ_EINVAL;
-	    }
-	    cur_acc->reg_uri = pj_str(pj_optarg);
-	    break;
-
-	case OPT_REG_TIMEOUT:   /* reg-timeout */
-	    cur_acc->reg_timeout = pj_strtoul(pj_cstr(&tmp,pj_optarg));
-	    if (cur_acc->reg_timeout < 1 || cur_acc->reg_timeout > 3600) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid value for --reg-timeout "
-			  "(expecting 1-3600)"));
-		return PJ_EINVAL;
-	    }
-	    break;
-
-	case OPT_PUBLISH:   /* publish */
-	    cur_acc->publish_enabled = PJ_TRUE;
-	    break;
-
-	case OPT_MWI:	/* mwi */
-	    cur_acc->mwi_enabled = PJ_TRUE;
-	    break;
-
-	case OPT_100REL: /** 100rel */
-	    cur_acc->require_100rel = PJSUA_100REL_MANDATORY;
-	    cfg->cfg.require_100rel = PJSUA_100REL_MANDATORY;
-	    break;
-
-	case OPT_TIMER: /** session timer */
-	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (lval < 0 || lval > 3) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: expecting integer value 0-3 for --use-timer"));
-		return PJ_EINVAL;
-	    }
-	    cur_acc->use_timer = lval;
-	    cfg->cfg.use_timer = lval;
-	    break;
-
-	case OPT_TIMER_SE: /** session timer session expiration */
-	    cur_acc->timer_setting.sess_expires = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (cur_acc->timer_setting.sess_expires < 90) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid value for --timer-se "
-			  "(expecting higher than 90)"));
-		return PJ_EINVAL;
-	    }
-	    cfg->cfg.timer_setting.sess_expires = cur_acc->timer_setting.sess_expires;
-	    break;
-
-	case OPT_TIMER_MIN_SE: /** session timer minimum session expiration */
-	    cur_acc->timer_setting.min_se = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (cur_acc->timer_setting.min_se < 90) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid value for --timer-min-se "
-			  "(expecting higher than 90)"));
-		return PJ_EINVAL;
-	    }
-	    cfg->cfg.timer_setting.min_se = cur_acc->timer_setting.min_se;
-	    break;
-
-	case OPT_OUTB_RID: /* Outbound reg-id */
-	    cur_acc->rfc5626_reg_id = pj_str(pj_optarg);
-	    break;
-
-	case OPT_USE_IMS: /* Activate IMS settings */
-	    cur_acc->auth_pref.initial_auth = PJ_TRUE;
-	    break;
-
-	case OPT_ID:   /* id */
-	    if (pjsua_verify_url(pj_optarg) != 0) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid SIP URL '%s' "
-			  "in local id argument", pj_optarg));
-		return PJ_EINVAL;
-	    }
-	    cur_acc->id = pj_str(pj_optarg);
-	    break;
-
-	case OPT_CONTACT:   /* contact */
-	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid SIP URL '%s' "
-			  "in contact argument", pj_optarg));
-		return PJ_EINVAL;
-	    }
-	    cur_acc->force_contact = pj_str(pj_optarg);
-	    break;
-
-	case OPT_CONTACT_PARAMS:
-	    cur_acc->contact_params = pj_str(pj_optarg);
-	    break;
-
-	case OPT_CONTACT_URI_PARAMS:
-	    cur_acc->contact_uri_params = pj_str(pj_optarg);
-	    break;
-
-	case OPT_AUTO_UPDATE_NAT:   /* OPT_AUTO_UPDATE_NAT */
-            cur_acc->allow_contact_rewrite  = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    break;
-
-	case OPT_DISABLE_STUN:
-	    cur_acc->sip_stun_use = PJSUA_STUN_USE_DISABLED;
-	    cur_acc->media_stun_use = PJSUA_STUN_USE_DISABLED;
-	    break;
-
-	case OPT_USE_COMPACT_FORM:
-	    /* enable compact form - from Ticket #342 */
-            {
-		extern pj_bool_t pjsip_use_compact_form;
-		extern pj_bool_t pjsip_include_allow_hdr_in_dlg;
-		extern pj_bool_t pjmedia_add_rtpmap_for_static_pt;
-
-		pjsip_use_compact_form = PJ_TRUE;
-		/* do not transmit Allow header */
-		pjsip_include_allow_hdr_in_dlg = PJ_FALSE;
-		/* Do not include rtpmap for static payload types (<96) */
-		pjmedia_add_rtpmap_for_static_pt = PJ_FALSE;
-            }
-	    break;
-
-	case OPT_ACCEPT_REDIRECT:
-	    cfg->redir_op = my_atoi(pj_optarg);
-	    if (cfg->redir_op<0 || cfg->redir_op>PJSIP_REDIRECT_STOP) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: accept-redirect value '%s' ", pj_optarg));
-		return PJ_EINVAL;
-	    }
-	    break;
-
-	case OPT_NO_FORCE_LR:
-	    cfg->cfg.force_lr = PJ_FALSE;
-	    break;
-
-	case OPT_NEXT_ACCOUNT: /* Add more account. */
-	    cfg->acc_cnt++;
-	    cur_acc = &cfg->acc_cfg[cfg->acc_cnt];
-	    break;
-
-	case OPT_USERNAME:   /* Default authentication user */
-	    cur_acc->cred_info[cur_acc->cred_count].username = pj_str(pj_optarg);
-	    cur_acc->cred_info[cur_acc->cred_count].scheme = pj_str("Digest");
-	    break;
-
-	case OPT_REALM:	    /* Default authentication realm. */
-	    cur_acc->cred_info[cur_acc->cred_count].realm = pj_str(pj_optarg);
-	    break;
-
-	case OPT_PASSWORD:   /* authentication password */
-	    cur_acc->cred_info[cur_acc->cred_count].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
-	    cur_acc->cred_info[cur_acc->cred_count].data = pj_str(pj_optarg);
-#if PJSIP_HAS_DIGEST_AKA_AUTH
-	    cur_acc->cred_info[cur_acc->cred_count].data_type |= PJSIP_CRED_DATA_EXT_AKA;
-	    cur_acc->cred_info[cur_acc->cred_count].ext.aka.k = pj_str(pj_optarg);
-	    cur_acc->cred_info[cur_acc->cred_count].ext.aka.cb = &pjsip_auth_create_aka_response;
-#endif
-	    break;
-
-	case OPT_REG_RETRY_INTERVAL:
-	    cur_acc->reg_retry_interval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    break;
-
-	case OPT_REG_USE_PROXY:
-	    cur_acc->reg_use_proxy = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg));
-	    if (cur_acc->reg_use_proxy > 3) {
-		PJ_LOG(1,(THIS_FILE, "Error: invalid --reg-use-proxy value '%s'",
-			  pj_optarg));
-		return PJ_EINVAL;
-	    }
-	    break;
-
-	case OPT_NEXT_CRED: /* next credential */
-	    cur_acc->cred_count++;
-	    break;
-
-	case OPT_NAMESERVER: /* nameserver */
-	    cfg->cfg.nameserver[cfg->cfg.nameserver_count++] = pj_str(pj_optarg);
-	    if (cfg->cfg.nameserver_count > PJ_ARRAY_SIZE(cfg->cfg.nameserver)) {
-		PJ_LOG(1,(THIS_FILE, "Error: too many nameservers"));
-		return PJ_ETOOMANY;
-	    }
-	    break;
-
-	case OPT_STUN_SRV:   /* STUN server */
-	    cfg->cfg.stun_host = pj_str(pj_optarg);
-	    if (cfg->cfg.stun_srv_cnt==PJ_ARRAY_SIZE(cfg->cfg.stun_srv)) {
-		PJ_LOG(1,(THIS_FILE, "Error: too many STUN servers"));
-		return PJ_ETOOMANY;
-	    }
-	    cfg->cfg.stun_srv[cfg->cfg.stun_srv_cnt++] = pj_str(pj_optarg);
-	    break;
-
-	case OPT_ADD_BUDDY: /* Add to buddy list. */
-	    if (pjsua_verify_url(pj_optarg) != 0) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: invalid URL '%s' in "
-			  "--add-buddy option", pj_optarg));
-		return -1;
-	    }
-	    if (cfg->buddy_cnt == PJ_ARRAY_SIZE(cfg->buddy_cfg)) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: too many buddies in buddy list."));
-		return -1;
-	    }
-	    cfg->buddy_cfg[cfg->buddy_cnt].uri = pj_str(pj_optarg);
-	    cfg->buddy_cnt++;
-	    break;
-
-	case OPT_AUTO_PLAY:
-	    cfg->auto_play = 1;
-	    break;
-
-	case OPT_AUTO_PLAY_HANGUP:
-	    cfg->auto_play_hangup = 1;
-	    break;
-
-	case OPT_AUTO_REC:
-	    cfg->auto_rec = 1;
-	    break;
-
-	case OPT_AUTO_LOOP:
-	    cfg->auto_loop = 1;
-	    break;
-
-	case OPT_AUTO_CONF:
-	    cfg->auto_conf = 1;
-	    break;
-
-	case OPT_PLAY_FILE:
-	    cfg->wav_files[cfg->wav_count++] = pj_str(pj_optarg);
-	    break;
-
-	case OPT_PLAY_TONE:
-	    {
-		int f1, f2, on, off;
-		int n;
-
-		n = sscanf(pj_optarg, "%d,%d,%d,%d", &f1, &f2, &on, &off);
-		if (n != 4) {
-		    puts("Expecting f1,f2,on,off in --play-tone");
-		    return -1;
-		}
-
-		cfg->tones[cfg->tone_count].freq1 = (short)f1;
-		cfg->tones[cfg->tone_count].freq2 = (short)f2;
-		cfg->tones[cfg->tone_count].on_msec = (short)on;
-		cfg->tones[cfg->tone_count].off_msec = (short)off;
-		++cfg->tone_count;
-	    }
-	    break;
-
-	case OPT_REC_FILE:
-	    cfg->rec_file = pj_str(pj_optarg);
-	    break;
-
-	case OPT_USE_ICE:
-	    cfg->media_cfg.enable_ice =
-		    cur_acc->ice_cfg.enable_ice = PJ_TRUE;
-	    break;
-
-	case OPT_ICE_REGULAR:
-	    cfg->media_cfg.ice_opt.aggressive =
-		    cur_acc->ice_cfg.ice_opt.aggressive = PJ_FALSE;
-	    break;
-
-	case OPT_USE_TURN:
-	    cfg->media_cfg.enable_turn =
-		    cur_acc->turn_cfg.enable_turn = PJ_TRUE;
-	    break;
-
-	case OPT_ICE_MAX_HOSTS:
-	    cfg->media_cfg.ice_max_host_cands =
-		    cur_acc->ice_cfg.ice_max_host_cands = my_atoi(pj_optarg);
-	    break;
-
-	case OPT_ICE_NO_RTCP:
-	    cfg->media_cfg.ice_no_rtcp =
-		    cur_acc->ice_cfg.ice_no_rtcp = PJ_TRUE;
-	    break;
-
-	case OPT_TURN_SRV:
-	    cfg->media_cfg.turn_server =
-		    cur_acc->turn_cfg.turn_server = pj_str(pj_optarg);
-	    break;
-
-	case OPT_TURN_TCP:
-	    cfg->media_cfg.turn_conn_type =
-		    cur_acc->turn_cfg.turn_conn_type = PJ_TURN_TP_TCP;
-	    break;
-
-	case OPT_TURN_USER:
-	    cfg->media_cfg.turn_auth_cred.type =
-		    cur_acc->turn_cfg.turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC;
-	    cfg->media_cfg.turn_auth_cred.data.static_cred.realm =
-		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.realm = pj_str("*");
-	    cfg->media_cfg.turn_auth_cred.data.static_cred.username =
-		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.username = pj_str(pj_optarg);
-	    break;
-
-	case OPT_TURN_PASSWD:
-	    cfg->media_cfg.turn_auth_cred.data.static_cred.data_type =
-		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
-	    cfg->media_cfg.turn_auth_cred.data.static_cred.data =
-		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data = pj_str(pj_optarg);
-	    break;
-
-#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
-	case OPT_USE_SRTP:
-	    app_config.cfg.use_srtp = my_atoi(pj_optarg);
-	    if (!pj_isdigit(*pj_optarg) || app_config.cfg.use_srtp > 3) {
-		PJ_LOG(1,(THIS_FILE, "Invalid value for --use-srtp option"));
-		return -1;
-	    }
-	    if ((int)app_config.cfg.use_srtp == 3) {
-		/* SRTP optional mode with duplicated media offer */
-		app_config.cfg.use_srtp = PJMEDIA_SRTP_OPTIONAL;
-		app_config.cfg.srtp_optional_dup_offer = PJ_TRUE;
-		cur_acc->srtp_optional_dup_offer = PJ_TRUE;
-	    }
-	    cur_acc->use_srtp = app_config.cfg.use_srtp;
-	    break;
-	case OPT_SRTP_SECURE:
-	    app_config.cfg.srtp_secure_signaling = my_atoi(pj_optarg);
-	    if (!pj_isdigit(*pj_optarg) || 
-		app_config.cfg.srtp_secure_signaling > 2) 
-	    {
-		PJ_LOG(1,(THIS_FILE, "Invalid value for --srtp-secure option"));
-		return -1;
-	    }
-	    cur_acc->srtp_secure_signaling = app_config.cfg.srtp_secure_signaling;
-	    break;
-#endif
-
-	case OPT_RTP_PORT:
-	    cfg->rtp_cfg.port = my_atoi(pj_optarg);
-	    if (cfg->rtp_cfg.port == 0) {
-		enum { START_PORT=4000 };
-		unsigned range;
-
-		range = (65535-START_PORT-PJSUA_MAX_CALLS*2);
-		cfg->rtp_cfg.port = START_PORT + 
-				    ((pj_rand() % range) & 0xFFFE);
-	    }
-
-	    if (cfg->rtp_cfg.port < 1 || cfg->rtp_cfg.port > 65535) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: rtp-port argument value "
-			  "(expecting 1-65535"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_DIS_CODEC:
-            cfg->codec_dis[cfg->codec_dis_cnt++] = pj_str(pj_optarg);
-	    break;
-
-	case OPT_ADD_CODEC:
-	    cfg->codec_arg[cfg->codec_cnt++] = pj_str(pj_optarg);
-	    break;
-
-	/* These options were no longer valid after new pjsua */
-	/*
-	case OPT_COMPLEXITY:
-	    cfg->complexity = my_atoi(pj_optarg);
-	    if (cfg->complexity < 0 || cfg->complexity > 10) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid --complexity (expecting 0-10"));
-		return -1;
-	    }
-	    break;
-	*/
-
-	case OPT_DURATION:
-	    cfg->duration = my_atoi(pj_optarg);
-	    break;
-
-	case OPT_THREAD_CNT:
-	    cfg->cfg.thread_cnt = my_atoi(pj_optarg);
-	    if (cfg->cfg.thread_cnt > 128) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid --thread-cnt option"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_PTIME:
-	    cfg->media_cfg.ptime = my_atoi(pj_optarg);
-	    if (cfg->media_cfg.ptime < 10 || cfg->media_cfg.ptime > 1000) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid --ptime option"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_NO_VAD:
-	    cfg->media_cfg.no_vad = PJ_TRUE;
-	    break;
-
-	case OPT_EC_TAIL:
-	    cfg->media_cfg.ec_tail_len = my_atoi(pj_optarg);
-	    if (cfg->media_cfg.ec_tail_len > 1000) {
-		PJ_LOG(1,(THIS_FILE, "I think the ec-tail length setting "
-			  "is too big"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_EC_OPT:
-	    cfg->media_cfg.ec_options = my_atoi(pj_optarg);
-	    break;
-
-	case OPT_QUALITY:
-	    cfg->media_cfg.quality = my_atoi(pj_optarg);
-	    if (cfg->media_cfg.quality < 0 || cfg->media_cfg.quality > 10) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid --quality (expecting 0-10"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_ILBC_MODE:
-	    cfg->media_cfg.ilbc_mode = my_atoi(pj_optarg);
-	    if (cfg->media_cfg.ilbc_mode!=20 && cfg->media_cfg.ilbc_mode!=30) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid --ilbc-mode (expecting 20 or 30"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_RX_DROP_PCT:
-	    cfg->media_cfg.rx_drop_pct = my_atoi(pj_optarg);
-	    if (cfg->media_cfg.rx_drop_pct > 100) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid --rx-drop-pct (expecting <= 100"));
-		return -1;
-	    }
-	    break;
-	    
-	case OPT_TX_DROP_PCT:
-	    cfg->media_cfg.tx_drop_pct = my_atoi(pj_optarg);
-	    if (cfg->media_cfg.tx_drop_pct > 100) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid --tx-drop-pct (expecting <= 100"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_AUTO_ANSWER:
-	    cfg->auto_answer = my_atoi(pj_optarg);
-	    if (cfg->auto_answer < 100 || cfg->auto_answer > 699) {
-		PJ_LOG(1,(THIS_FILE,
-			  "Error: invalid code in --auto-answer "
-			  "(expecting 100-699"));
-		return -1;
-	    }
-	    break;
-
-	case OPT_MAX_CALLS:
-	    cfg->cfg.max_calls = my_atoi(pj_optarg);
-	    if (cfg->cfg.max_calls < 1 || cfg->cfg.max_calls > PJSUA_MAX_CALLS) {
-		PJ_LOG(1,(THIS_FILE,"Error: maximum call setting exceeds "
-				    "compile time limit (PJSUA_MAX_CALLS=%d)",
-			  PJSUA_MAX_CALLS));
-		return -1;
-	    }
-	    break;
-
-#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
-	case OPT_USE_TLS:
-	    cfg->use_tls = PJ_TRUE;
-	    break;
-	    
-	case OPT_TLS_CA_FILE:
-	    cfg->udp_cfg.tls_setting.ca_list_file = pj_str(pj_optarg);
-	    break;
-	    
-	case OPT_TLS_CERT_FILE:
-	    cfg->udp_cfg.tls_setting.cert_file = pj_str(pj_optarg);
-	    break;
-	    
-	case OPT_TLS_PRIV_FILE:
-	    cfg->udp_cfg.tls_setting.privkey_file = pj_str(pj_optarg);
-	    break;
-
-	case OPT_TLS_PASSWORD:
-	    cfg->udp_cfg.tls_setting.password = pj_str(pj_optarg);
-	    break;
-
-	case OPT_TLS_VERIFY_SERVER:
-	    cfg->udp_cfg.tls_setting.verify_server = PJ_TRUE;
-	    break;
-
-	case OPT_TLS_VERIFY_CLIENT:
-	    cfg->udp_cfg.tls_setting.verify_client = PJ_TRUE;
-	    cfg->udp_cfg.tls_setting.require_client_cert = PJ_TRUE;
-	    break;
-
-	case OPT_TLS_NEG_TIMEOUT:
-	    cfg->udp_cfg.tls_setting.timeout.sec = atoi(pj_optarg);
-	    break;
-
-	case OPT_TLS_CIPHER:
-	    {
-		pj_ssl_cipher cipher;
-
-		if (pj_ansi_strnicmp(pj_optarg, "0x", 2) == 0) {
-		    pj_str_t cipher_st = pj_str(pj_optarg + 2);
-		    cipher = pj_strtoul2(&cipher_st, NULL, 16);
-		} else {
-		    cipher = atoi(pj_optarg);
-		}
-
-		if (pj_ssl_cipher_is_supported(cipher)) {
-		    static pj_ssl_cipher tls_ciphers[128];
-
-		    tls_ciphers[cfg->udp_cfg.tls_setting.ciphers_num++] = cipher;
-		    cfg->udp_cfg.tls_setting.ciphers = tls_ciphers;
-		} else {
-		    pj_ssl_cipher ciphers[128];
-		    unsigned j, ciphers_cnt;
-
-		    ciphers_cnt = PJ_ARRAY_SIZE(ciphers);
-		    pj_ssl_cipher_get_availables(ciphers, &ciphers_cnt);
-		    
-		    PJ_LOG(1,(THIS_FILE, "Cipher \"%s\" is not supported by "
-					 "TLS/SSL backend.", pj_optarg));
-		    printf("Available TLS/SSL ciphers (%d):\n", ciphers_cnt);
-		    for (j=0; j<ciphers_cnt; ++j)
-			printf("- 0x%06X: %s\n", ciphers[j], pj_ssl_cipher_name(ciphers[j]));
-		    return -1;
-		}
-	    }
- 	    break;
-#endif /* PJSIP_HAS_TLS_TRANSPORT */
-
-	case OPT_CAPTURE_DEV:
-	    cfg->capture_dev = atoi(pj_optarg);
-	    break;
-
-	case OPT_PLAYBACK_DEV:
-	    cfg->playback_dev = atoi(pj_optarg);
-	    break;
-
-	case OPT_STDOUT_REFRESH:
-	    stdout_refresh = atoi(pj_optarg);
-	    break;
-
-	case OPT_STDOUT_REFRESH_TEXT:
-	    stdout_refresh_text = pj_optarg;
-	    break;
-
-#ifdef _IONBF
-	case OPT_STDOUT_NO_BUF:
-	    setvbuf(stdout, NULL, _IONBF, 0);
-	    break;
-#endif
-
-	case OPT_CAPTURE_LAT:
-	    cfg->capture_lat = atoi(pj_optarg);
-	    break;
-
-	case OPT_PLAYBACK_LAT:
-	    cfg->playback_lat = atoi(pj_optarg);
-	    break;
-
-	case OPT_SND_AUTO_CLOSE:
-	    cfg->media_cfg.snd_auto_close_time = atoi(pj_optarg);
-	    break;
-
-	case OPT_NO_TONES:
-	    cfg->no_tones = PJ_TRUE;
-	    break;
-
-	case OPT_JB_MAX_SIZE:
-	    cfg->media_cfg.jb_max = atoi(pj_optarg);
-	    break;
-
-#if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6
-	case OPT_IPV6:
-	    cfg->ipv6 = PJ_TRUE;
-	    break;
-#endif
-	case OPT_QOS:
-	    cfg->enable_qos = PJ_TRUE;
-	    /* Set RTP traffic type to Voice */
-	    cfg->rtp_cfg.qos_type = PJ_QOS_TYPE_VOICE;
-	    /* Directly apply DSCP value to SIP traffic. Say lets
-	     * set it to CS3 (DSCP 011000). Note that this will not 
-	     * work on all platforms.
-	     */
-	    cfg->udp_cfg.qos_params.flags = PJ_QOS_PARAM_HAS_DSCP;
-	    cfg->udp_cfg.qos_params.dscp_val = 0x18;
-	    break;
-	case OPT_VIDEO:
-	    cfg->vid.vid_cnt = 1;
-	    cfg->vid.in_auto_show = PJ_TRUE;
-	    cfg->vid.out_auto_transmit = PJ_TRUE;
-	    break;
-	case OPT_EXTRA_AUDIO:
-	    cfg->aud_cnt++;
-	    break;
-
-	case OPT_VCAPTURE_DEV:
-	    cfg->vid.vcapture_dev = atoi(pj_optarg);
-	    cur_acc->vid_cap_dev = cfg->vid.vcapture_dev;
-	    break;
-
-	case OPT_VRENDER_DEV:
-	    cfg->vid.vrender_dev = atoi(pj_optarg);
-	    cur_acc->vid_rend_dev = cfg->vid.vrender_dev;
-	    break;
-
-	case OPT_PLAY_AVI:
-	    if (app_config.avi_cnt >= MAX_AVI) {
-		PJ_LOG(1,(THIS_FILE, "Too many AVIs"));
-		return -1;
-	    }
-	    app_config.avi[app_config.avi_cnt++].path = pj_str(pj_optarg);
-	    break;
-
-	case OPT_AUTO_PLAY_AVI:
-	    app_config.avi_auto_play = PJ_TRUE;
-	    break;
-
-	case OPT_USE_CLI:
-	    cfg->use_cli = PJ_TRUE;
-	    break;
-
-	case OPT_CLI_TELNET_PORT:
-	    cfg->cli_telnet_port = atoi(pj_optarg);
-	    break;
-
-	default:
-	    PJ_LOG(1,(THIS_FILE, 
-		      "Argument \"%s\" is not valid. Use --help to see help",
-		      argv[pj_optind-1]));
-	    return -1;
-	}
-    }
-
-    if (pj_optind != argc) {
-	pj_str_t uri_arg;
-
-	if (pjsua_verify_url(argv[pj_optind]) != PJ_SUCCESS) {
-	    PJ_LOG(1,(THIS_FILE, "Invalid SIP URI %s", argv[pj_optind]));
-	    return -1;
-	}
-	uri_arg = pj_str(argv[pj_optind]);
-	if (uri_to_call)
-	    *uri_to_call = uri_arg;
-	pj_optind++;
-
-	/* Add URI to call to buddy list if it's not already there */
-	for (i=0; i<cfg->buddy_cnt; ++i) {
-	    if (pj_stricmp(&cfg->buddy_cfg[i].uri, &uri_arg)==0)
-		break;
-	}
-	if (i == cfg->buddy_cnt && cfg->buddy_cnt < PJSUA_MAX_BUDDIES) {
-	    cfg->buddy_cfg[cfg->buddy_cnt++].uri = uri_arg;
-	}
-
-    } else {
-	if (uri_to_call)
-	    uri_to_call->slen = 0;
-    }
-
-    if (pj_optind != argc) {
-	PJ_LOG(1,(THIS_FILE, "Error: unknown options %s", argv[pj_optind]));
-	return PJ_EINVAL;
-    }
-
-    if (cfg->acc_cfg[cfg->acc_cnt].id.slen)
-	cfg->acc_cnt++;
-
-    for (i=0; i<cfg->acc_cnt; ++i) {
-	pjsua_acc_config *acfg = &cfg->acc_cfg[i];
-
-	if (acfg->cred_info[acfg->cred_count].username.slen)
-	{
-	    acfg->cred_count++;
-	}
-
-	if (acfg->ice_cfg.enable_ice) {
-	    acfg->ice_cfg_use = PJSUA_ICE_CONFIG_USE_CUSTOM;
-	}
-	if (acfg->turn_cfg.enable_turn) {
-	    acfg->turn_cfg_use = PJSUA_TURN_CONFIG_USE_CUSTOM;
-	}
-
-	/* When IMS mode is enabled for the account, verify that settings
-	 * are okay.
-	 */
-	/* For now we check if IMS mode is activated by looking if
-	 * initial_auth is set.
-	 */
-	if (acfg->auth_pref.initial_auth && acfg->cred_count) {
-	    /* Realm must point to the real domain */
-	    if (*acfg->cred_info[0].realm.ptr=='*') {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: cannot use '*' as realm with IMS"));
-		return PJ_EINVAL;
-	    }
-
-	    /* Username for authentication must be in a@b format */
-	    if (strchr(acfg->cred_info[0].username.ptr, '@')==0) {
-		PJ_LOG(1,(THIS_FILE, 
-			  "Error: Username for authentication must "
-			  "be in user@domain format with IMS"));
-		return PJ_EINVAL;
-	    }
-	}
-    }
-    return PJ_SUCCESS;
-}
-
 /*****************************************************************************
- * Console application
+ * Callback 
  */
 static void ringback_start(pjsua_call_id call_id)
@@ -1659,5 +219,5 @@
 	/* Cancel duration timer, if any */
 	if (app_config.call_data[call_id].timer.id != PJSUA_INVALID_ID) {
-	    struct call_data *cd = &app_config.call_data[call_id];
+	    app_call_data *cd = &app_config.call_data[call_id];
 	    pjsip_endpoint *endpt = pjsua_get_pjsip_endpt();
 
@@ -1696,5 +256,5 @@
 	{
 	    /* Schedule timer to hangup call after the specified duration */
-	    struct call_data *cd = &app_config.call_data[call_id];
+	    app_call_data *cd = &app_config.call_data[call_id];
 	    pjsip_endpoint *endpt = pjsua_get_pjsip_endpt();
 	    pj_time_val delay;
@@ -1810,5 +370,4 @@
     }
 }
-
 
 /*
@@ -2690,9 +1249,104 @@
 };
 
+#if defined(PJ_WIN32) && PJ_WIN32!=0
+#include <windows.h>
+
+static pj_thread_desc handler_desc;
+
+static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
+{   
+    switch (fdwCtrlType) 
+    { 
+        // Handle the CTRL+C signal. 
+ 
+        case CTRL_C_EVENT: 
+        case CTRL_CLOSE_EVENT: 
+        case CTRL_BREAK_EVENT: 
+        case CTRL_LOGOFF_EVENT: 
+        case CTRL_SHUTDOWN_EVENT: 
+	    pj_thread_register("ctrlhandler", handler_desc, &sig_thread);
+	    PJ_LOG(3,(THIS_FILE, "Ctrl-C detected, quitting.."));
+	    receive_end_sig = PJ_TRUE;
+            app_destroy();	    
+	    ExitProcess(1);
+            PJ_UNREACHED(return TRUE;)
+ 
+        default: 
+ 
+            return FALSE; 
+    } 
+}
+
+static void setup_socket_signal()
+{
+}
+
+#else
+#include <signal.h>
+
+static void setup_socket_signal()
+{
+    signal(SIGPIPE, SIG_IGN);
+}
+
+#endif
+
+static pj_status_t setup_pjsua()
+{
+    pj_status_t status = pjsua_destroy();
+    if (status != PJ_SUCCESS)
+	return status;
+
+    /* Create pjsua */
+    status = pjsua_create();
+    if (status != PJ_SUCCESS)
+	return status;
+
+    /* Create pool for application */
+    app_config.pool = pjsua_pool_create("pjsua-app", 1000, 1000);
+
+    return status;
+}
+
 /*****************************************************************************
  * Public API
  */
 
-pj_status_t app_init(int argc, char *argv[])
+#if defined(PJ_WIN32) && PJ_WIN32!=0
+PJ_DEF(void) setup_signal_handler(void)
+{
+    SetConsoleCtrlHandler(&CtrlHandler, TRUE);
+}
+#else
+PJ_DEF(void) setup_signal_handler(void)
+{
+}
+#endif
+
+int stdout_refresh_proc(void *arg)
+{
+    extern char *stdout_refresh_text;
+
+    PJ_UNUSED_ARG(arg);
+
+    /* Set thread to lowest priority so that it doesn't clobber
+     * stdout output
+     */
+    pj_thread_set_prio(pj_thread_this(), 
+		       pj_thread_get_prio_min(pj_thread_this()));
+
+    while (!stdout_refresh_quit) {
+	pj_thread_sleep(stdout_refresh * 1000);
+	puts(stdout_refresh_text);
+	fflush(stdout);
+    }
+
+    return 0;
+}
+
+PJ_DEF(pj_status_t) app_init(pj_cli_telnet_on_started on_started_cb,
+			     pj_cli_on_quit on_quit_cb,
+			     pj_cli_on_destroy on_destroy_cb,
+			     pj_cli_on_restart_pjsua on_restart_pjsua_cb)
 {
     pjsua_transport_id transport_id = -1;
@@ -2701,21 +1355,20 @@
     pj_status_t status;
 
-    app_restart = PJ_FALSE;
-
-    /* Create pjsua */
-    status = pjsua_create();
+    /** Setup pjsua **/
+    status = setup_pjsua();
     if (status != PJ_SUCCESS)
 	return status;
 
-    /* Create pool for application */
-    app_config.pool = pjsua_pool_create("pjsua-app", 1000, 1000);
-
-    /* Initialize default config */
-    default_config(&app_config);
-    
-    /* Parse the arguments */
-    status = parse_args(argc, argv, &app_config, &uri_arg);
+    /** Load config **/
+    status = load_config(&app_config, &uri_arg, app_running);
     if (status != PJ_SUCCESS)
-	return status;
+	return status;	    
+
+#if defined(PJ_SYMBIAN) && PJ_SYMBIAN!=0
+    /* Disable threading on Symbian */
+    app_config.cfg.thread_cnt = 0;
+    app_config.media_cfg.thread_cnt = 0;
+    app_config.media_cfg.has_ioqueue = PJ_FALSE;
+#endif
 
     /* Initialize application callbacks */
@@ -3237,14 +1890,20 @@
     }
 
+    /* Init call setting */
+    pjsua_call_setting_default(&call_opt);
+    call_opt.aud_cnt = app_config.aud_cnt;
+    call_opt.vid_cnt = app_config.vid.vid_cnt;    
+
+    /* Init CLI if configured */    
     if (app_config.use_cli) {
-	/*
-	 * Init CLI
-	 */    
-	status = setup_cli();
-	if (status != PJ_SUCCESS)
-	    goto on_error;
-	
-	PJ_LOG(3,(THIS_FILE, "CLI telnet daemon listening at port %d", 
-		  app_config.cli_telnet_port));
+	if (app_restart) {
+	    pj_uint16_t port = (pj_uint16_t)app_config.cli_telnet_port;
+	    status = setup_cli(!app_config.disable_cli_console, 
+			       app_config.cli_telnet_port >= 0, port,
+			       on_started_cb, on_quit_cb, on_destroy_cb,
+			       on_restart_pjsua_cb);
+	    if (status != PJ_SUCCESS)
+		goto on_error;
+	}
     }
 
@@ -3252,4 +1911,5 @@
 
 on_error:
+    app_restart = PJ_FALSE;
     app_destroy();
     return status;
@@ -3259,12 +1919,4 @@
 {
     pj_thread_t *stdout_refresh_thread = NULL;
-    pj_status_t status;
-
-    /* Start pjsua */
-    status = pjsua_start();
-    if (status != PJ_SUCCESS) {
-	app_destroy();
-	return status;
-    }
 
     /* Start console refresh thread */
@@ -3275,7 +1927,7 @@
 
     if (app_config.use_cli)
-	cli_console_app_main(&uri_arg, &app_restart);
-    else 
-	console_app_main(&uri_arg, &app_restart);
+	start_cli_main(&uri_arg, &app_restart);	
+    else
+	start_ui_main(&uri_arg, &app_restart);
 
     if (stdout_refresh_thread) {
@@ -3288,5 +1940,5 @@
 }
 
-pj_status_t app_destroy(void)
+pj_status_t app_destroy()
 {
     pj_status_t status;
@@ -3344,5 +1996,5 @@
 
     if (app_config.use_cli) {	
-	destroy_cli();
+	destroy_cli(app_restart);
     }
 
@@ -3351,12 +2003,72 @@
 	app_config.pool = NULL;
     }
-
+    
     status = pjsua_destroy();
-
-    pj_bzero(&app_config, sizeof(app_config));
-
+    
+    if (!app_restart)
+	pj_bzero(&app_config, sizeof(app_config));
+    
     return status;
 }
 
+/** === CLI Callback == **/
+
+static void cli_telnet_started(pj_cli_telnet_info *telnet_info)
+{    
+    PJ_LOG(3,(THIS_FILE, "Telnet daemon listening at %.*s:%d", 
+	      telnet_info->ip_address.slen, telnet_info->ip_address.ptr,
+	      telnet_info->port));
+}
+
+static void cli_on_quit (pj_bool_t is_restarted)
+{
+    PJ_LOG(3,(THIS_FILE, "CLI quit, restart(%d)", is_restarted));
+}
+
+static void cli_on_destroy(void)
+{
+    PJ_LOG(3,(THIS_FILE, "CLI destroyed"));
+}
+
+static void cli_on_restart_pjsua(void)
+{
+    PJ_LOG(3,(THIS_FILE, "Restart pjsua"));
+}
+
+/** ======================= **/
+
+int main_func(int argc, char *argv[])
+{
+    pj_status_t status;
+
+    setup_socket_signal();
+
+    receive_end_sig = PJ_FALSE;
+    app_restart = PJ_TRUE;
+
+    add_startup_config(argc, argv);    
+
+    do {
+	if (app_restart) {	    
+	    status = app_init(cli_telnet_started, cli_on_quit,
+			      cli_on_destroy, cli_on_restart_pjsua);
+	    if (status != PJ_SUCCESS)
+		return 1;	    
+	}	
+
+	app_running = PJ_TRUE;
+
+	app_main();
+	if (!receive_end_sig) {
+	    app_destroy();
+
+	    /* This is on purpose */
+	    app_destroy();
+	} else {
+	    pj_thread_join(sig_thread);
+	}
+    } while (app_restart);
+    return 0;
+}
 
 #ifdef STEREO_DEMO
@@ -3431,3 +2143,2 @@
 }
 #endif
-
Index: /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cli.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cli.c	(revision 4461)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cli.c	(revision 4461)
@@ -0,0 +1,269 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
+ * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.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 
+ */
+
+#include "pjsua_common.h"
+#include <pjlib-util/cli.h>
+#include <pjlib-util/cli_imp.h>
+#include <pjlib-util/cli_console.h>
+#include <pjlib-util/cli_telnet.h>
+#include <pjlib-util/scanner.h>
+
+#define THIS_FILE	"pjsua_cli.c"
+
+pj_cli_telnet_on_started   cli_telnet_on_started_cb = NULL;
+pj_cli_on_quit	   	   cli_on_quit_cb = NULL;
+pj_cli_on_destroy	   cli_on_destroy_cb = NULL;
+pj_cli_on_restart_pjsua	   cli_on_restart_pjsua_cb = NULL;
+
+pj_bool_t		   pjsua_restarted = PJ_TRUE;
+static pj_bool_t	   pj_inited = PJ_FALSE;
+static pj_caching_pool	   cli_cp;
+static pj_cli_t		   *cli = NULL;
+static pj_cli_sess	   *cli_cons_sess = NULL;
+
+/** Forward declaration **/
+pj_status_t setup_command(pj_cli_t *cli);
+
+static void log_writer(int level, const char *buffer, int len)
+{
+    if (cli)
+	pj_cli_write_log(cli, level, buffer, len);
+
+    if (app_config.disable_cli_console)
+	pj_log_write(level, buffer, len);
+}
+
+void destroy_cli(pj_bool_t app_restart)
+{    
+    pj_log_set_log_func(&pj_log_write);
+    
+    if (cli) {		
+	pj_cli_destroy(cli);
+	cli = NULL;
+    }
+
+    if (cli_cp.factory.create_pool) {
+	pj_caching_pool_destroy(&cli_cp);
+	pj_bzero(&cli_cp, sizeof(cli_cp));
+    }
+
+    if (pj_inited) {
+	pj_shutdown();
+	pj_inited = PJ_FALSE;
+    }
+    if (!app_restart) {
+	if (cli_on_destroy_cb)
+	    (*cli_on_destroy_cb)();
+    }
+}
+
+pj_status_t setup_cli(pj_bool_t with_console, pj_bool_t with_telnet,
+		      pj_uint16_t telnet_port, 
+		      pj_cli_telnet_on_started on_started_cb,
+		      pj_cli_on_quit on_quit_cb,
+		      pj_cli_on_destroy on_destroy_cb,
+		      pj_cli_on_restart_pjsua on_restart_pjsua_cb)
+{
+    pj_cli_cfg cli_cfg;
+    pj_status_t status;
+
+    /* Destroy CLI if initialized */
+    destroy_cli(PJ_TRUE);
+
+    /* Init PJLIB */
+    status = pj_init();
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    pj_inited = PJ_TRUE;
+
+    /* Init PJLIB-UTIL */
+    status = pjlib_util_init();
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    /* Init CLI */
+    pj_caching_pool_init(&cli_cp, NULL, 0);
+    pj_cli_cfg_default(&cli_cfg);
+    cli_cfg.pf = &cli_cp.factory;
+    cli_cfg.name = pj_str("pjsua_cli");
+    cli_cfg.title = pj_str("Pjsua CLI Application");
+    status = pj_cli_create(&cli_cfg, &cli);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    status = setup_command(cli);
+    if (status != PJ_SUCCESS)
+	goto on_error;
+
+    if (on_destroy_cb)
+	cli_on_destroy_cb = on_destroy_cb;
+
+    if (on_restart_pjsua_cb)
+	cli_on_restart_pjsua_cb = on_restart_pjsua_cb;
+
+    if (on_quit_cb)
+	cli_on_quit_cb = on_quit_cb;
+
+    /* Init telnet frontend */
+    if (with_telnet) {
+	pj_cli_telnet_cfg telnet_cfg;
+	pj_pool_t *pool;
+
+	pool = pj_pool_create(&cli_cp.factory, "cli_cp", 128, 128, NULL);
+	pj_assert(pool);
+
+	pj_cli_telnet_cfg_default(&telnet_cfg);
+	telnet_cfg.log_level = 5;
+	telnet_cfg.port = telnet_port;
+	if (on_started_cb)
+	    cli_telnet_on_started_cb = on_started_cb;
+
+	telnet_cfg.on_started = cli_telnet_on_started_cb;
+
+	status = pj_cli_telnet_create(cli, &telnet_cfg, NULL);
+	if (status != PJ_SUCCESS)
+	    goto on_error;
+    }
+
+    /* Init console frontend */
+    if (with_console) {
+	pj_cli_console_cfg console_cfg;
+	
+	pj_cli_console_cfg_default(&console_cfg);
+	console_cfg.quit_command = pj_str("shutdown");
+	status = pj_cli_console_create(cli, &console_cfg,
+				       &cli_cons_sess, NULL);
+	if (status != PJ_SUCCESS)
+	    goto on_error;
+    }
+
+    return PJ_SUCCESS;
+
+on_error:
+    destroy_cli(PJ_FALSE);
+    return status;
+}
+
+PJ_DEF(pj_bool_t) is_cli_inited()
+{
+    return (cli != NULL);
+}
+
+static pj_status_t setup_timer(pj_timer_heap_t **timer, 
+			       pj_ioqueue_t **ioqueue)
+{
+    pj_status_t status = pj_timer_heap_create(app_config.pool, 16, timer);
+
+    if (status != PJ_SUCCESS)
+	return status;
+
+    status = pj_ioqueue_create(app_config.pool, 16, ioqueue);    
+
+    return status;
+}
+
+static pj_status_t stop_timer(pj_timer_heap_t *timer, 
+			      pj_ioqueue_t *ioqueue)
+{
+    if ((!timer) || (!ioqueue))
+	return PJ_SUCCESS;
+
+    pj_timer_heap_destroy(timer);
+
+    return pj_ioqueue_destroy(ioqueue);
+}
+
+pj_status_t cli_pjsua_start(pj_str_t *uri_to_call, 
+			    pj_timer_heap_t **main_timer_heap, 
+			    pj_ioqueue_t **main_ioqueue)
+{
+    pj_status_t status = PJ_SUCCESS;
+
+    pjsua_restarted = PJ_FALSE;
+
+    if (app_config.disable_cli_console) {
+	status = setup_timer(main_timer_heap, main_ioqueue);
+	if (status != PJ_SUCCESS)
+	    return status;
+    }
+
+    status = pjsua_start();
+    if (status != PJ_SUCCESS)
+	return status;
+
+    pj_log_set_log_func(&log_writer);
+
+    setup_signal_handler();
+
+    /* If user specifies URI to call, then call the URI */
+    if (uri_to_call->slen) {
+	pjsua_call_make_call(current_acc, uri_to_call, &call_opt, NULL, 
+			     NULL, NULL);
+    }
+
+    if (!app_config.disable_cli_console)
+	PJ_LOG(3,(THIS_FILE, "CLI console is ready, press '?' for help"));
+
+    return status;
+}
+
+void start_cli_main(pj_str_t *uri_to_call, pj_bool_t *app_restart)
+{    
+    pj_status_t status;
+    char cmdline[PJ_CLI_MAX_CMDBUF];
+    pj_timer_heap_t *main_timer_heap = NULL;
+    pj_ioqueue_t *main_ioqueue = NULL;    
+
+    *app_restart = PJ_FALSE;
+    pjsua_restarted = PJ_TRUE;
+
+    do {
+	if (pjsua_restarted) {
+	    status = cli_pjsua_start(uri_to_call, &main_timer_heap, 
+				     &main_ioqueue);
+
+	    if (status != PJ_SUCCESS)
+		return;
+	}
+
+	if (app_config.disable_cli_console) {
+	    pj_time_val delay = {0, 10};
+	    pj_ioqueue_poll(main_ioqueue, &delay);
+	    if (pj_cli_is_quitting(cli))
+		continue;
+	    pj_timer_heap_poll(main_timer_heap, NULL);     
+	} else {
+	    pj_cli_console_process(cli_cons_sess, &cmdline[0], sizeof(cmdline));
+	}
+	if (pjsua_restarted) {
+	    status = stop_timer(main_timer_heap, main_ioqueue);
+	    if (status != PJ_SUCCESS)
+		return;
+	    
+	    status = app_init(NULL, NULL, NULL, NULL);
+	    if (status != PJ_SUCCESS)
+		return;
+	}
+
+    } while (!pj_cli_is_quitting(cli));
+    stop_timer(main_timer_heap, main_ioqueue);
+    *app_restart = pj_cli_is_restarting(cli);
+}
Index: /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cli_cmd.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cli_cmd.c	(revision 4460)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cli_cmd.c	(revision 4461)
@@ -19,11 +19,15 @@
  */
 
-#include "pjsua_cmd.h"
+#include "pjsua_common.h"
 #include <pjlib-util/cli.h>
 #include <pjlib-util/cli_imp.h>
 #include <pjlib-util/cli_console.h>
 #include <pjlib-util/cli_telnet.h>
+#include <pjlib-util/scanner.h>
 
 #define THIS_FILE	"pjsua_cli_cmd.c"
+
+#define CHECK_PJSUA_RUNNING() if (pjsua_get_state()!=PJSUA_STATE_RUNNING) \
+				  return PJ_EINVALIDOP
 
 /* CLI command id */
@@ -39,4 +43,6 @@
 #define CMD_NETWORK		    900
 #define CMD_QUIT		    110
+#define CMD_RESTART		    120
+#define CMD_RELOAD		    130
 
 /* call level 2 command */
@@ -144,15 +150,9 @@
 #define DYN_CHOICE_ADDED_BUDDY_ID   (DYN_CHOICE_START)+12
 
-static pj_cli_cfg cli_cfg;
-static pj_cli_telnet_cfg telnet_cfg;
-static pj_cli_t *cli = NULL;
-static pj_cli_sess *sess = NULL;
-static pj_cli_console_cfg console_cfg;
-
 /* Get input URL */
 static void get_input_url(char *buf, 
 			  int len,
 			  pj_cli_cmd_val *cval,
-struct input_result *result)
+			  struct input_result *result)
 {
     static const pj_str_t err_invalid_input = {"Invalid input\n", 15};
@@ -203,5 +203,5 @@
 
 	pj_cli_sess_write_msg(cval->sess, err_invalid_input.ptr, 
-	    err_invalid_input.slen);
+			      err_invalid_input.slen);
 	result->nb_result = NO_NB;
 	return;
@@ -616,37 +616,6 @@
     default:
 	param->cnt = 0;
-    }
-}
-
-void cli_console_app_main(const pj_str_t *uri_to_call, pj_bool_t *app_restart)
-{        
-    pjsua_call_setting_default(&call_opt);
-    call_opt.aud_cnt = app_config.aud_cnt;
-    call_opt.vid_cnt = app_config.vid.vid_cnt;    
-
-    /* If user specifies URI to call, then call the URI */
-    if (uri_to_call->slen) {
-	pjsua_call_make_call(current_acc, uri_to_call, &call_opt, NULL, 
-			     NULL, NULL);
-    }
-
-    /*
-     * Main loop.
-     */
-    for (;;) {
-	char cmdline[PJ_CLI_MAX_CMDBUF];	
-        pj_status_t status;
-
-        status = pj_cli_console_process(sess, &cmdline[0], sizeof(cmdline));
-
-	if (status == PJ_CLI_EEXIT) {
-	    /* exit is called */
-	    break;
-	} else if (status != PJ_SUCCESS) {
-	    /* Something wrong with the cmdline */
-	    PJ_PERROR(1,(THIS_FILE, status, "Exec error"));
-	}
-    }    
-    *app_restart = pj_cli_is_restarting(cli);  
+	break;
+    }
 }
 
@@ -795,4 +764,6 @@
 {    
     pj_status_t status = PJ_SUCCESS;
+
+    CHECK_PJSUA_RUNNING();
 
     switch(pj_cli_get_cmd_id(cval->cmd)) {
@@ -1065,4 +1036,6 @@
     pj_status_t status = PJ_SUCCESS;
 
+    CHECK_PJSUA_RUNNING();
+
     switch(pj_cli_get_cmd_id(cval->cmd)) {
     case CMD_PRESENCE_ADD_BUDDY:
@@ -1107,6 +1080,6 @@
 
     for (i=0; i<count; ++i) {
-	char out_str[PJSUA_MAX_CALLS*6];
-	char txlist[PJSUA_MAX_CALLS*4+10];
+	char out_str[128];
+	char txlist[16];
 	unsigned j;
 	pjsua_conf_port_info info;
@@ -1224,4 +1197,6 @@
     pj_status_t status = PJ_SUCCESS;
 
+    CHECK_PJSUA_RUNNING();
+
     switch(pj_cli_get_cmd_id(cval->cmd)) {
     case CMD_MEDIA_LIST:
@@ -1306,4 +1281,6 @@
 {
     pj_status_t status = PJ_SUCCESS;
+
+    CHECK_PJSUA_RUNNING();
 
     switch(pj_cli_get_cmd_id(cval->cmd)) {
@@ -1524,5 +1501,4 @@
 {
     if (current_call != PJSUA_INVALID_ID) {
-	call_opt.flag |= PJSUA_CALL_UNHOLD;
 	pjsua_call_update2(current_call, &call_opt, NULL);
     } else {
@@ -1923,4 +1899,6 @@
     pj_cli_cmd_id cmd_id = pj_cli_get_cmd_id(cval->cmd);
 
+    CHECK_PJSUA_RUNNING();
+
     switch(cmd_id) {
     case CMD_CALL_NEW:
@@ -2012,4 +1990,6 @@
     pjsua_acc_config acc_cfg;
     pj_cli_cmd_id cmd_id = pj_cli_get_cmd_id(cval->cmd);
+
+    CHECK_PJSUA_RUNNING();
 
     pjsua_acc_get_config(current_acc, &acc_cfg);
@@ -2322,4 +2302,6 @@
     pj_cli_cmd_id cmd_id = pj_cli_get_cmd_id(cval->cmd);    
 
+    CHECK_PJSUA_RUNNING();
+
     switch(cmd_id) {
     case CMD_VIDEO_ENABLE:
@@ -2415,5 +2397,8 @@
 {
     pj_status_t status = PJ_SUCCESS;
-    PJ_UNUSED_ARG(cval);    
+    PJ_UNUSED_ARG(cval);
+
+    CHECK_PJSUA_RUNNING();
+    
     status = pjsua_detect_nat_type();
     if (status != PJ_SUCCESS)
@@ -2425,6 +2410,11 @@
 static pj_status_t cmd_quit_handler(pj_cli_cmd_val *cval)
 {
+    extern pj_cli_on_quit cli_on_quit_cb;
     PJ_LOG(3,(THIS_FILE, "Quitting app.."));
-    pj_cli_quit(cval->sess->fe->cli, cval->sess, PJ_FALSE);    
+    pj_cli_quit(cval->sess->fe->cli, cval->sess, PJ_FALSE);
+    /** Call pj_cli_on_quit callback **/
+    if (cli_on_quit_cb)
+	(*cli_on_quit_cb)(PJ_FALSE);
+
     return PJ_SUCCESS;
 }
@@ -2432,6 +2422,69 @@
 static pj_status_t cmd_restart_handler(pj_cli_cmd_val *cval)
 {
+    extern pj_cli_on_quit cli_on_quit_cb;
     PJ_LOG(3,(THIS_FILE, "Restarting app.."));
-    pj_cli_quit(cval->sess->fe->cli, cval->sess, PJ_TRUE);    
+    pj_cli_quit(cval->sess->fe->cli, cval->sess, PJ_TRUE);
+    /** Call pj_cli_on_quit callback **/
+    if (cli_on_quit_cb)
+	(*cli_on_quit_cb)(PJ_TRUE);
+
+    return PJ_SUCCESS;
+}
+
+/* 
+ * Syntax error handler for parser. 
+ */
+static void on_syntax_error(pj_scanner *scanner)
+{
+    PJ_UNUSED_ARG(scanner);
+    PJ_THROW(PJ_EINVAL);
+}
+
+static pj_status_t get_options(pj_str_t *options, unsigned *cmd_count)
+{
+    pj_scanner scanner;
+    pj_str_t str;
+    
+    PJ_USE_EXCEPTION;
+
+    if (!options)
+	return PJ_SUCCESS;
+
+    pj_scan_init(&scanner, options->ptr, options->slen, PJ_SCAN_AUTOSKIP_WS, 
+		 &on_syntax_error);
+    PJ_TRY {
+	while (!pj_scan_is_eof(&scanner)) {	    
+	    ++(*cmd_count);
+	    pj_scan_get_until_chr(&scanner, " \t\r\n", &str);
+	    /** Store to command arguments **/	    
+	    add_reload_config(*cmd_count, &str);	    
+	}
+    }
+    PJ_CATCH_ANY {
+	pj_scan_fini(&scanner);	
+	return PJ_GET_EXCEPTION();
+    }
+    PJ_END;
+    return PJ_SUCCESS;
+}
+
+static pj_status_t cmd_reload_handler(pj_cli_cmd_val *cval)
+{
+    int i;
+    unsigned cmd_count = 0;
+    extern pj_bool_t pjsua_restarted;
+    extern pj_cli_on_restart_pjsua cli_on_restart_pjsua_cb;
+
+    PJ_LOG(3,(THIS_FILE, "Reloading Pjsua.."));
+    /** Get the pjsua option **/       
+    
+    for (i=1;i<cval->argc;i++) {
+	get_options(&cval->argv[i], &cmd_count);
+    }
+    pjsua_restarted = PJ_TRUE;
+
+    if (cli_on_restart_pjsua_cb)
+	(*cli_on_restart_pjsua_cb)();
+
     return PJ_SUCCESS;
 }
@@ -2832,4 +2885,12 @@
 	"<CMD name='restart' id='120' desc='Restart application'/>";
 
+    char* reload_command =
+	"<CMD name='reload' id='130' desc='Reload pjsua'>"
+	"  <ARG name='options1' type='string' desc='Options' optional='1'/>"
+	"  <ARG name='options2' type='string' desc='Options' optional='1'/>"
+	"  <ARG name='options3' type='string' desc='Options' optional='1'/>"
+	"  <ARG name='options4' type='string' desc='Options' optional='1'/>"
+	"</CMD>";
+
     pj_status_t status;
     pj_str_t sleep_xml = pj_str(sleep_command);    
@@ -2837,4 +2898,5 @@
     pj_str_t shutdown_xml = pj_str(shutdown_command);
     pj_str_t restart_xml = pj_str(restart_command);
+    pj_str_t reload_xml = pj_str(reload_command);
 
     status = pj_cli_add_cmd_from_xml(cli, NULL, 
@@ -2860,9 +2922,15 @@
 				     &restart_xml, cmd_restart_handler, 
 				     NULL, NULL);
+    if (status != PJ_SUCCESS)
+	return status;
+
+    status = pj_cli_add_cmd_from_xml(cli, NULL, 
+				     &reload_xml, cmd_reload_handler, 
+				     NULL, NULL);
 
     return status;
 }
 
-static pj_status_t setup_command()
+pj_status_t setup_command(pj_cli_t *cli)
 {
     pj_status_t status;
@@ -2898,57 +2966,2 @@
     return status;
 }
-
-static void log_writer(int level, const char *buffer, int len)
-{
-    if (cli)
-	pj_cli_write_log(cli, level, buffer, len);
-}
-
-pj_status_t setup_cli()
-{
-    pj_status_t status;    
-    pj_cli_cfg_default(&cli_cfg);
-    cli_cfg.pf = app_config.pool->factory;    
-    cli_cfg.name = pj_str("pjsua_cli");
-    cli_cfg.title = pj_str("Pjsua CLI Application");
-
-    status = pj_cli_create(&cli_cfg, &cli);
-    if (status != PJ_SUCCESS)
-	return status;
-
-    status = setup_command();
-    if (status != PJ_SUCCESS)
-	return status;
-
-    pj_log_set_log_func(&log_writer);
-
-    /* 
-    * Init telnet
-    */ 
-    pj_cli_telnet_cfg_default(&telnet_cfg);
-    telnet_cfg.log_level = 5;
-    if (app_config.cli_telnet_port)
-	telnet_cfg.port = (pj_uint16_t)app_config.cli_telnet_port;
-
-    status = pj_cli_telnet_create(cli, &telnet_cfg, NULL);
-    if (status != PJ_SUCCESS)
-	return status;
-
-    app_config.cli_telnet_port = telnet_cfg.port;;
-
-    /*
-    * Init console
-    */ 
-    pj_cli_console_cfg_default(&console_cfg);
-    console_cfg.quit_command = pj_str("shutdown");
-    status = pj_cli_console_create(cli, &console_cfg, &sess, NULL);
-    return status;
-}
-
-void destroy_cli()
-{
-    pj_log_set_log_func(&pj_log_write);    
-    pj_cli_destroy(cli);
-    cli = NULL;  
-}
-
Index: project/trunk/pjsip-apps/src/pjsua/pjsua_cmd.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cmd.c	(revision 4460)
+++ 	(revision )
@@ -1,1028 +1,0 @@
-/* $Id$ */
-/* 
- * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
- * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.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 
- */
-
-#include "pjsua_cmd.h"
-
-#define THIS_FILE	"pjsua_cmd.c"
-
-#if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0)
-#   define SOME_BUF_SIZE	(1024 * 10)
-#else
-#   define SOME_BUF_SIZE	(1024 * 3)
-#endif
-
-static char some_buf[SOME_BUF_SIZE];
-
-/** Variable definition **/
-int		    stdout_refresh = -1;
-pj_bool_t	    stdout_refresh_quit = PJ_FALSE;
-pjsua_call_id	    current_call = PJSUA_INVALID_ID;
-pjsua_app_config    app_config;
-pjsua_call_setting  call_opt;
-pjsua_msg_data	    msg_data;
-
-PJ_DEF(int) my_atoi(const char *cs)
-{
-    pj_str_t s;
-
-    pj_cstr(&s, cs);
-    if (cs[0] == '-') {
-	s.ptr++, s.slen--;
-	return 0 - (int)pj_strtoul(&s);
-    } else if (cs[0] == '+') {
-	s.ptr++, s.slen--;
-	return pj_strtoul(&s);
-    } else {
-	return pj_strtoul(&s);
-    }
-}
-
-/*
- * Find next call when current call is disconnected or when user
- * press ']'
- */
-PJ_DEF(pj_bool_t) find_next_call()
-{
-    int i, max;
-
-    max = pjsua_call_get_max_count();
-    for (i=current_call+1; i<max; ++i) {
-	if (pjsua_call_is_active(i)) {
-	    current_call = i;
-	    return PJ_TRUE;
-	}
-    }
-
-    for (i=0; i<current_call; ++i) {
-	if (pjsua_call_is_active(i)) {
-	    current_call = i;
-	    return PJ_TRUE;
-	}
-    }
-
-    current_call = PJSUA_INVALID_ID;
-    return PJ_FALSE;
-}
-
-PJ_DEF(pj_bool_t) find_prev_call()
-{
-    int i, max;
-
-    max = pjsua_call_get_max_count();
-    for (i=current_call-1; i>=0; --i) {
-	if (pjsua_call_is_active(i)) {
-	    current_call = i;
-	    return PJ_TRUE;
-	}
-    }
-
-    for (i=max-1; i>current_call; --i) {
-	if (pjsua_call_is_active(i)) {
-	    current_call = i;
-	    return PJ_TRUE;
-	}
-    }
-
-    current_call = PJSUA_INVALID_ID;
-    return PJ_FALSE;
-}
-
-/*
- * Send arbitrary request to remote host
- */
-PJ_DEF(void) send_request(char *cstr_method, const pj_str_t *dst_uri)
-{
-    pj_str_t str_method;
-    pjsip_method method;
-    pjsip_tx_data *tdata;
-    pjsip_endpoint *endpt;
-    pj_status_t status;
-
-    endpt = pjsua_get_pjsip_endpt();
-
-    str_method = pj_str(cstr_method);
-    pjsip_method_init_np(&method, &str_method);
-
-    status = pjsua_acc_create_request(current_acc, &method, dst_uri, &tdata);
-
-    status = pjsip_endpt_send_request(endpt, tdata, -1, NULL, NULL);
-    if (status != PJ_SUCCESS) {
-	pjsua_perror(THIS_FILE, "Unable to send request", status);
-	return;
-    }
-}
-
-/*
- * Print log of call states. Since call states may be too long for logger,
- * printing it is a bit tricky, it should be printed part by part as long 
- * as the logger can accept.
- */
-PJ_DEF(void) log_call_dump(int call_id) 
-{
-    unsigned call_dump_len;
-    unsigned part_len;
-    unsigned part_idx;
-    unsigned log_decor;
-
-    pjsua_call_dump(call_id, PJ_TRUE, some_buf, sizeof(some_buf), "  ");
-    call_dump_len = strlen(some_buf);
-
-    log_decor = pj_log_get_decor();
-    pj_log_set_decor(log_decor & ~(PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_CR));
-    PJ_LOG(3,(THIS_FILE, "\n"));
-    pj_log_set_decor(0);
-
-    part_idx = 0;
-    part_len = PJ_LOG_MAX_SIZE-80;
-    while (part_idx < call_dump_len) {
-	char p_orig, *p;
-
-	p = &some_buf[part_idx];
-	if (part_idx + part_len > call_dump_len)
-	    part_len = call_dump_len - part_idx;
-	p_orig = p[part_len];
-	p[part_len] = '\0';
-	PJ_LOG(3,(THIS_FILE, "%s", p));
-	p[part_len] = p_orig;
-	part_idx += part_len;
-    }
-    pj_log_set_decor(log_decor);
-}
-
-/*
- * Save account settings
- */
-static void write_account_settings(int acc_index, pj_str_t *result)
-{
-    unsigned i;
-    char line[128];
-    pjsua_acc_config *acc_cfg = &app_config.acc_cfg[acc_index];
-
-    
-    pj_ansi_sprintf(line, "\n#\n# Account %d:\n#\n", acc_index);
-    pj_strcat2(result, line);
-
-
-    /* Identity */
-    if (acc_cfg->id.slen) {
-	pj_ansi_sprintf(line, "--id %.*s\n", 
-			(int)acc_cfg->id.slen, 
-			acc_cfg->id.ptr);
-	pj_strcat2(result, line);
-    }
-
-    /* Registrar server */
-    if (acc_cfg->reg_uri.slen) {
-	pj_ansi_sprintf(line, "--registrar %.*s\n",
-			      (int)acc_cfg->reg_uri.slen,
-			      acc_cfg->reg_uri.ptr);
-	pj_strcat2(result, line);
-
-	pj_ansi_sprintf(line, "--reg-timeout %u\n",
-			      acc_cfg->reg_timeout);
-	pj_strcat2(result, line);
-    }
-
-    /* Contact */
-    if (acc_cfg->force_contact.slen) {
-	pj_ansi_sprintf(line, "--contact %.*s\n", 
-			(int)acc_cfg->force_contact.slen, 
-			acc_cfg->force_contact.ptr);
-	pj_strcat2(result, line);
-    }
-
-    /* Contact header parameters */
-    if (acc_cfg->contact_params.slen) {
-	pj_ansi_sprintf(line, "--contact-params %.*s\n", 
-			(int)acc_cfg->contact_params.slen, 
-			acc_cfg->contact_params.ptr);
-	pj_strcat2(result, line);
-    }
-
-    /* Contact URI parameters */
-    if (acc_cfg->contact_uri_params.slen) {
-	pj_ansi_sprintf(line, "--contact-uri-params %.*s\n", 
-			(int)acc_cfg->contact_uri_params.slen, 
-			acc_cfg->contact_uri_params.ptr);
-	pj_strcat2(result, line);
-    }
-
-    /*  */
-    if (acc_cfg->allow_contact_rewrite!=1)
-    {
-	pj_ansi_sprintf(line, "--auto-update-nat %i\n",
-			(int)acc_cfg->allow_contact_rewrite);
-	pj_strcat2(result, line);
-    }
-
-#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
-    /* SRTP */
-    if (acc_cfg->use_srtp) {
-	int use_srtp = (int)acc_cfg->use_srtp;
-	if (use_srtp == PJMEDIA_SRTP_OPTIONAL && 
-	    acc_cfg->srtp_optional_dup_offer)
-	{
-	    use_srtp = 3;
-	}
-	pj_ansi_sprintf(line, "--use-srtp %i\n", use_srtp);
-	pj_strcat2(result, line);
-    }
-    if (acc_cfg->srtp_secure_signaling != 
-	PJSUA_DEFAULT_SRTP_SECURE_SIGNALING) 
-    {
-	pj_ansi_sprintf(line, "--srtp-secure %d\n",
-			acc_cfg->srtp_secure_signaling);
-	pj_strcat2(result, line);
-    }
-#endif
-
-    /* Proxy */
-    for (i=0; i<acc_cfg->proxy_cnt; ++i) {
-	pj_ansi_sprintf(line, "--proxy %.*s\n",
-			      (int)acc_cfg->proxy[i].slen,
-			      acc_cfg->proxy[i].ptr);
-	pj_strcat2(result, line);
-    }
-
-    /* Credentials */
-    for (i=0; i<acc_cfg->cred_count; ++i) {
-	if (acc_cfg->cred_info[i].realm.slen) {
-	    pj_ansi_sprintf(line, "--realm %.*s\n",
-				  (int)acc_cfg->cred_info[i].realm.slen,
-				  acc_cfg->cred_info[i].realm.ptr);
-	    pj_strcat2(result, line);
-	}
-
-	if (acc_cfg->cred_info[i].username.slen) {
-	    pj_ansi_sprintf(line, "--username %.*s\n",
-				  (int)acc_cfg->cred_info[i].username.slen,
-				  acc_cfg->cred_info[i].username.ptr);
-	    pj_strcat2(result, line);
-	}
-
-	if (acc_cfg->cred_info[i].data.slen) {
-	    pj_ansi_sprintf(line, "--password %.*s\n",
-				  (int)acc_cfg->cred_info[i].data.slen,
-				  acc_cfg->cred_info[i].data.ptr);
-	    pj_strcat2(result, line);
-	}
-
-	if (i != acc_cfg->cred_count - 1)
-	    pj_strcat2(result, "--next-cred\n");
-    }
-
-    /* reg-use-proxy */
-    if (acc_cfg->reg_use_proxy != 3) {
-	pj_ansi_sprintf(line, "--reg-use-proxy %d\n",
-			      acc_cfg->reg_use_proxy);
-	pj_strcat2(result, line);
-    }
-
-    /* rereg-delay */
-    if (acc_cfg->reg_retry_interval != PJSUA_REG_RETRY_INTERVAL) {
-	pj_ansi_sprintf(line, "--rereg-delay %d\n",
-		              acc_cfg->reg_retry_interval);
-	pj_strcat2(result, line);
-    }
-
-    /* 100rel extension */
-    if (acc_cfg->require_100rel) {
-	pj_strcat2(result, "--use-100rel\n");
-    }
-
-    /* Session Timer extension */
-    if (acc_cfg->use_timer) {
-	pj_ansi_sprintf(line, "--use-timer %d\n",
-			      acc_cfg->use_timer);
-	pj_strcat2(result, line);
-    }
-    if (acc_cfg->timer_setting.min_se != 90) {
-	pj_ansi_sprintf(line, "--timer-min-se %d\n",
-			      acc_cfg->timer_setting.min_se);
-	pj_strcat2(result, line);
-    }
-    if (acc_cfg->timer_setting.sess_expires != PJSIP_SESS_TIMER_DEF_SE) {
-	pj_ansi_sprintf(line, "--timer-se %d\n",
-			      acc_cfg->timer_setting.sess_expires);
-	pj_strcat2(result, line);
-    }
-
-    /* Publish */
-    if (acc_cfg->publish_enabled)
-	pj_strcat2(result, "--publish\n");
-
-    /* MWI */
-    if (acc_cfg->mwi_enabled)
-	pj_strcat2(result, "--mwi\n");
-
-    if (acc_cfg->sip_stun_use != PJSUA_STUN_USE_DEFAULT ||
-	acc_cfg->media_stun_use != PJSUA_STUN_USE_DEFAULT)
-    {
-	pj_strcat2(result, "--disable-stun\n");
-    }
-
-    /* Media Transport*/
-    if (acc_cfg->ice_cfg.enable_ice)
-	pj_strcat2(result, "--use-ice\n");
-
-    if (acc_cfg->ice_cfg.ice_opt.aggressive == PJ_FALSE)
-	pj_strcat2(result, "--ice-regular\n");
-
-    if (acc_cfg->turn_cfg.enable_turn)
-	pj_strcat2(result, "--use-turn\n");
-
-    if (acc_cfg->ice_cfg.ice_max_host_cands >= 0) {
-	pj_ansi_sprintf(line, "--ice_max_host_cands %d\n",
-	                acc_cfg->ice_cfg.ice_max_host_cands);
-	pj_strcat2(result, line);
-    }
-
-    if (acc_cfg->ice_cfg.ice_no_rtcp)
-	pj_strcat2(result, "--ice-no-rtcp\n");
-
-    if (acc_cfg->turn_cfg.turn_server.slen) {
-	pj_ansi_sprintf(line, "--turn-srv %.*s\n",
-			(int)acc_cfg->turn_cfg.turn_server.slen,
-			acc_cfg->turn_cfg.turn_server.ptr);
-	pj_strcat2(result, line);
-    }
-
-    if (acc_cfg->turn_cfg.turn_conn_type == PJ_TURN_TP_TCP)
-	pj_strcat2(result, "--turn-tcp\n");
-
-    if (acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.slen) {
-	pj_ansi_sprintf(line, "--turn-user %.*s\n",
-			(int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.slen,
-			acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.ptr);
-	pj_strcat2(result, line);
-    }
-
-    if (acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.slen) {
-	pj_ansi_sprintf(line, "--turn-passwd %.*s\n",
-			(int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.slen,
-			acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.ptr);
-	pj_strcat2(result, line);
-    }
-}
-
-/*
- * Write settings.
- */
-PJ_DEF(int) write_settings(pjsua_app_config *config, char *buf, pj_size_t max)
-{
-    unsigned acc_index;
-    unsigned i;
-    pj_str_t cfg;
-    char line[128];
-    extern pj_bool_t pjsip_use_compact_form;
-
-    PJ_UNUSED_ARG(max);
-
-    cfg.ptr = buf;
-    cfg.slen = 0;
-
-    /* Logging. */
-    pj_strcat2(&cfg, "#\n# Logging options:\n#\n");
-    pj_ansi_sprintf(line, "--log-level %d\n",
-		    config->log_cfg.level);
-    pj_strcat2(&cfg, line);
-
-    pj_ansi_sprintf(line, "--app-log-level %d\n",
-		    config->log_cfg.console_level);
-    pj_strcat2(&cfg, line);
-
-    if (config->log_cfg.log_filename.slen) {
-	pj_ansi_sprintf(line, "--log-file %.*s\n",
-			(int)config->log_cfg.log_filename.slen,
-			config->log_cfg.log_filename.ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    if (config->log_cfg.log_file_flags & PJ_O_APPEND) {
-	pj_strcat2(&cfg, "--log-append\n");
-    }
-
-    /* Save account settings. */
-    for (acc_index=0; acc_index < config->acc_cnt; ++acc_index) {
-	
-	write_account_settings(acc_index, &cfg);
-
-	if (acc_index < config->acc_cnt-1)
-	    pj_strcat2(&cfg, "--next-account\n");
-    }
-
-    pj_strcat2(&cfg, "\n#\n# Network settings:\n#\n");
-
-    /* Nameservers */
-    for (i=0; i<config->cfg.nameserver_count; ++i) {
-	pj_ansi_sprintf(line, "--nameserver %.*s\n",
-			      (int)config->cfg.nameserver[i].slen,
-			      config->cfg.nameserver[i].ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* Outbound proxy */
-    for (i=0; i<config->cfg.outbound_proxy_cnt; ++i) {
-	pj_ansi_sprintf(line, "--outbound %.*s\n",
-			      (int)config->cfg.outbound_proxy[i].slen,
-			      config->cfg.outbound_proxy[i].ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* Transport options */
-    if (config->ipv6) {
-	pj_strcat2(&cfg, "--ipv6\n");
-    }
-    if (config->enable_qos) {
-	pj_strcat2(&cfg, "--set-qos\n");
-    }
-
-    /* UDP Transport. */
-    pj_ansi_sprintf(line, "--local-port %d\n", config->udp_cfg.port);
-    pj_strcat2(&cfg, line);
-
-    /* IP address, if any. */
-    if (config->udp_cfg.public_addr.slen) {
-	pj_ansi_sprintf(line, "--ip-addr %.*s\n", 
-			(int)config->udp_cfg.public_addr.slen,
-			config->udp_cfg.public_addr.ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* Bound IP address, if any. */
-    if (config->udp_cfg.bound_addr.slen) {
-	pj_ansi_sprintf(line, "--bound-addr %.*s\n", 
-			(int)config->udp_cfg.bound_addr.slen,
-			config->udp_cfg.bound_addr.ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* No TCP ? */
-    if (config->no_tcp) {
-	pj_strcat2(&cfg, "--no-tcp\n");
-    }
-
-    /* No UDP ? */
-    if (config->no_udp) {
-	pj_strcat2(&cfg, "--no-udp\n");
-    }
-
-    /* STUN */
-    for (i=0; i<config->cfg.stun_srv_cnt; ++i) {
-	pj_ansi_sprintf(line, "--stun-srv %.*s\n",
-			(int)config->cfg.stun_srv[i].slen, 
-			config->cfg.stun_srv[i].ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
-    /* TLS */
-    if (config->use_tls)
-	pj_strcat2(&cfg, "--use-tls\n");
-    if (config->udp_cfg.tls_setting.ca_list_file.slen) {
-	pj_ansi_sprintf(line, "--tls-ca-file %.*s\n",
-			(int)config->udp_cfg.tls_setting.ca_list_file.slen, 
-			config->udp_cfg.tls_setting.ca_list_file.ptr);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->udp_cfg.tls_setting.cert_file.slen) {
-	pj_ansi_sprintf(line, "--tls-cert-file %.*s\n",
-			(int)config->udp_cfg.tls_setting.cert_file.slen, 
-			config->udp_cfg.tls_setting.cert_file.ptr);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->udp_cfg.tls_setting.privkey_file.slen) {
-	pj_ansi_sprintf(line, "--tls-privkey-file %.*s\n",
-			(int)config->udp_cfg.tls_setting.privkey_file.slen, 
-			config->udp_cfg.tls_setting.privkey_file.ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    if (config->udp_cfg.tls_setting.password.slen) {
-	pj_ansi_sprintf(line, "--tls-password %.*s\n",
-			(int)config->udp_cfg.tls_setting.password.slen, 
-			config->udp_cfg.tls_setting.password.ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    if (config->udp_cfg.tls_setting.verify_server)
-	pj_strcat2(&cfg, "--tls-verify-server\n");
-
-    if (config->udp_cfg.tls_setting.verify_client)
-	pj_strcat2(&cfg, "--tls-verify-client\n");
-
-    if (config->udp_cfg.tls_setting.timeout.sec) {
-	pj_ansi_sprintf(line, "--tls-neg-timeout %d\n",
-			(int)config->udp_cfg.tls_setting.timeout.sec);
-	pj_strcat2(&cfg, line);
-    }
-
-    for (i=0; i<config->udp_cfg.tls_setting.ciphers_num; ++i) {
-	pj_ansi_sprintf(line, "--tls-cipher 0x%06X # %s\n",
-			config->udp_cfg.tls_setting.ciphers[i],
-			pj_ssl_cipher_name(config->udp_cfg.tls_setting.ciphers[i]));
-	pj_strcat2(&cfg, line);
-    }
-#endif
-
-    pj_strcat2(&cfg, "\n#\n# Media settings:\n#\n");
-
-    /* Video & extra audio */
-    for (i=0; i<config->vid.vid_cnt; ++i) {
-	pj_strcat2(&cfg, "--video\n");
-    }
-    for (i=1; i<config->aud_cnt; ++i) {
-	pj_strcat2(&cfg, "--extra-audio\n");
-    }
-
-    /* SRTP */
-#if PJMEDIA_HAS_SRTP
-    if (app_config.cfg.use_srtp != PJSUA_DEFAULT_USE_SRTP) {
-	int use_srtp = (int)app_config.cfg.use_srtp;
-	if (use_srtp == PJMEDIA_SRTP_OPTIONAL && 
-	    app_config.cfg.srtp_optional_dup_offer)
-	{
-	    use_srtp = 3;
-	}
-	pj_ansi_sprintf(line, "--use-srtp %d\n", use_srtp);
-	pj_strcat2(&cfg, line);
-    }
-    if (app_config.cfg.srtp_secure_signaling != 
-	PJSUA_DEFAULT_SRTP_SECURE_SIGNALING) 
-    {
-	pj_ansi_sprintf(line, "--srtp-secure %d\n",
-			app_config.cfg.srtp_secure_signaling);
-	pj_strcat2(&cfg, line);
-    }
-#endif
-
-    /* Media */
-    if (config->null_audio)
-	pj_strcat2(&cfg, "--null-audio\n");
-    if (config->auto_play)
-	pj_strcat2(&cfg, "--auto-play\n");
-    if (config->auto_loop)
-	pj_strcat2(&cfg, "--auto-loop\n");
-    if (config->auto_conf)
-	pj_strcat2(&cfg, "--auto-conf\n");
-    for (i=0; i<config->wav_count; ++i) {
-	pj_ansi_sprintf(line, "--play-file %s\n",
-			config->wav_files[i].ptr);
-	pj_strcat2(&cfg, line);
-    }
-    for (i=0; i<config->tone_count; ++i) {
-	pj_ansi_sprintf(line, "--play-tone %d,%d,%d,%d\n",
-			config->tones[i].freq1, config->tones[i].freq2, 
-			config->tones[i].on_msec, config->tones[i].off_msec);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->rec_file.slen) {
-	pj_ansi_sprintf(line, "--rec-file %s\n",
-			config->rec_file.ptr);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->auto_rec)
-	pj_strcat2(&cfg, "--auto-rec\n");
-    if (config->capture_dev != PJSUA_INVALID_ID) {
-	pj_ansi_sprintf(line, "--capture-dev %d\n", config->capture_dev);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->playback_dev != PJSUA_INVALID_ID) {
-	pj_ansi_sprintf(line, "--playback-dev %d\n", config->playback_dev);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->media_cfg.snd_auto_close_time != -1) {
-	pj_ansi_sprintf(line, "--snd-auto-close %d\n", 
-			config->media_cfg.snd_auto_close_time);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->no_tones) {
-	pj_strcat2(&cfg, "--no-tones\n");
-    }
-    if (config->media_cfg.jb_max != -1) {
-	pj_ansi_sprintf(line, "--jb-max-size %d\n", 
-			config->media_cfg.jb_max);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* Sound device latency */
-    if (config->capture_lat != PJMEDIA_SND_DEFAULT_REC_LATENCY) {
-	pj_ansi_sprintf(line, "--capture-lat %d\n", config->capture_lat);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->playback_lat != PJMEDIA_SND_DEFAULT_PLAY_LATENCY) {
-	pj_ansi_sprintf(line, "--playback-lat %d\n", config->playback_lat);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* Media clock rate. */
-    if (config->media_cfg.clock_rate != PJSUA_DEFAULT_CLOCK_RATE) {
-	pj_ansi_sprintf(line, "--clock-rate %d\n",
-			config->media_cfg.clock_rate);
-	pj_strcat2(&cfg, line);
-    } else {
-	pj_ansi_sprintf(line, "#using default --clock-rate %d\n",
-			config->media_cfg.clock_rate);
-	pj_strcat2(&cfg, line);
-    }
-
-    if (config->media_cfg.snd_clock_rate && 
-	config->media_cfg.snd_clock_rate != config->media_cfg.clock_rate) 
-    {
-	pj_ansi_sprintf(line, "--snd-clock-rate %d\n",
-			config->media_cfg.snd_clock_rate);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* Stereo mode. */
-    if (config->media_cfg.channel_count == 2) {
-	pj_ansi_sprintf(line, "--stereo\n");
-	pj_strcat2(&cfg, line);
-    }
-
-    /* quality */
-    if (config->media_cfg.quality != PJSUA_DEFAULT_CODEC_QUALITY) {
-	pj_ansi_sprintf(line, "--quality %d\n",
-			config->media_cfg.quality);
-	pj_strcat2(&cfg, line);
-    } else {
-	pj_ansi_sprintf(line, "#using default --quality %d\n",
-			config->media_cfg.quality);
-	pj_strcat2(&cfg, line);
-    }
-
-    if (config->vid.vcapture_dev != PJMEDIA_VID_DEFAULT_CAPTURE_DEV) {
-	pj_ansi_sprintf(line, "--vcapture-dev %d\n", config->vid.vcapture_dev);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->vid.vrender_dev != PJMEDIA_VID_DEFAULT_RENDER_DEV) {
-	pj_ansi_sprintf(line, "--vrender-dev %d\n", config->vid.vrender_dev);
-	pj_strcat2(&cfg, line);
-    }
-    for (i=0; i<config->avi_cnt; ++i) {
-	pj_ansi_sprintf(line, "--play-avi %s\n", config->avi[i].path.ptr);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->avi_auto_play) {
-	pj_ansi_sprintf(line, "--auto-play-avi\n");
-	pj_strcat2(&cfg, line);
-    }
-
-    /* ptime */
-    if (config->media_cfg.ptime) {
-	pj_ansi_sprintf(line, "--ptime %d\n",
-			config->media_cfg.ptime);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* no-vad */
-    if (config->media_cfg.no_vad) {
-	pj_strcat2(&cfg, "--no-vad\n");
-    }
-
-    /* ec-tail */
-    if (config->media_cfg.ec_tail_len != PJSUA_DEFAULT_EC_TAIL_LEN) {
-	pj_ansi_sprintf(line, "--ec-tail %d\n",
-			config->media_cfg.ec_tail_len);
-	pj_strcat2(&cfg, line);
-    } else {
-	pj_ansi_sprintf(line, "#using default --ec-tail %d\n",
-			config->media_cfg.ec_tail_len);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* ec-opt */
-    if (config->media_cfg.ec_options != 0) {
-	pj_ansi_sprintf(line, "--ec-opt %d\n",
-			config->media_cfg.ec_options);
-	pj_strcat2(&cfg, line);
-    } 
-
-    /* ilbc-mode */
-    if (config->media_cfg.ilbc_mode != PJSUA_DEFAULT_ILBC_MODE) {
-	pj_ansi_sprintf(line, "--ilbc-mode %d\n",
-			config->media_cfg.ilbc_mode);
-	pj_strcat2(&cfg, line);
-    } else {
-	pj_ansi_sprintf(line, "#using default --ilbc-mode %d\n",
-			config->media_cfg.ilbc_mode);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* RTP drop */
-    if (config->media_cfg.tx_drop_pct) {
-	pj_ansi_sprintf(line, "--tx-drop-pct %d\n",
-			config->media_cfg.tx_drop_pct);
-	pj_strcat2(&cfg, line);
-
-    }
-    if (config->media_cfg.rx_drop_pct) {
-	pj_ansi_sprintf(line, "--rx-drop-pct %d\n",
-			config->media_cfg.rx_drop_pct);
-	pj_strcat2(&cfg, line);
-
-    }
-
-    /* Start RTP port. */
-    pj_ansi_sprintf(line, "--rtp-port %d\n",
-		    config->rtp_cfg.port);
-    pj_strcat2(&cfg, line);
-
-    /* Disable codec */
-    for (i=0; i<config->codec_dis_cnt; ++i) {
-	pj_ansi_sprintf(line, "--dis-codec %s\n",
-		    config->codec_dis[i].ptr);
-	pj_strcat2(&cfg, line);
-    }
-    /* Add codec. */
-    for (i=0; i<config->codec_cnt; ++i) {
-	pj_ansi_sprintf(line, "--add-codec %s\n",
-		    config->codec_arg[i].ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    pj_strcat2(&cfg, "\n#\n# User agent:\n#\n");
-
-    /* Auto-answer. */
-    if (config->auto_answer != 0) {
-	pj_ansi_sprintf(line, "--auto-answer %d\n",
-			config->auto_answer);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* accept-redirect */
-    if (config->redir_op != PJSIP_REDIRECT_ACCEPT_REPLACE) {
-	pj_ansi_sprintf(line, "--accept-redirect %d\n",
-			config->redir_op);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* Max calls. */
-    pj_ansi_sprintf(line, "--max-calls %d\n",
-		    config->cfg.max_calls);
-    pj_strcat2(&cfg, line);
-
-    /* Uas-duration. */
-    if (config->duration != NO_LIMIT_DURATION) {
-	pj_ansi_sprintf(line, "--duration %d\n",
-			config->duration);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* norefersub ? */
-    if (config->no_refersub) {
-	pj_strcat2(&cfg, "--norefersub\n");
-    }
-
-    if (pjsip_use_compact_form)
-    {
-	pj_strcat2(&cfg, "--use-compact-form\n");
-    }
-
-    if (!config->cfg.force_lr) {
-	pj_strcat2(&cfg, "--no-force-lr\n");
-    }
-
-    pj_strcat2(&cfg, "\n#\n# Buddies:\n#\n");
-
-    /* Add buddies. */
-    for (i=0; i<config->buddy_cnt; ++i) {
-	pj_ansi_sprintf(line, "--add-buddy %.*s\n",
-			      (int)config->buddy_cfg[i].uri.slen,
-			      config->buddy_cfg[i].uri.ptr);
-	pj_strcat2(&cfg, line);
-    }
-
-    /* SIP extensions. */
-    pj_strcat2(&cfg, "\n#\n# SIP extensions:\n#\n");
-    /* 100rel extension */
-    if (config->cfg.require_100rel) {
-	pj_strcat2(&cfg, "--use-100rel\n");
-    }
-    /* Session Timer extension */
-    if (config->cfg.use_timer) {
-	pj_ansi_sprintf(line, "--use-timer %d\n",
-			      config->cfg.use_timer);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->cfg.timer_setting.min_se != 90) {
-	pj_ansi_sprintf(line, "--timer-min-se %d\n",
-			      config->cfg.timer_setting.min_se);
-	pj_strcat2(&cfg, line);
-    }
-    if (config->cfg.timer_setting.sess_expires != PJSIP_SESS_TIMER_DEF_SE) {
-	pj_ansi_sprintf(line, "--timer-se %d\n",
-			      config->cfg.timer_setting.sess_expires);
-	pj_strcat2(&cfg, line);
-    }
-
-    *(cfg.ptr + cfg.slen) = '\0';
-    return cfg.slen;
-}
-
-#ifdef PJSUA_HAS_VIDEO
-PJ_DEF(void) app_config_init_video(pjsua_acc_config *acc_cfg)
-{
-    acc_cfg->vid_in_auto_show = app_config.vid.in_auto_show;
-    acc_cfg->vid_out_auto_transmit = app_config.vid.out_auto_transmit;
-    /* Note that normally GUI application will prefer a borderless
-     * window.
-     */
-    acc_cfg->vid_wnd_flags = PJMEDIA_VID_DEV_WND_BORDER |
-                             PJMEDIA_VID_DEV_WND_RESIZABLE;
-    acc_cfg->vid_cap_dev = app_config.vid.vcapture_dev;
-    acc_cfg->vid_rend_dev = app_config.vid.vrender_dev;
-
-    if (app_config.avi_auto_play &&
-	app_config.avi_def_idx != PJSUA_INVALID_ID &&
-	app_config.avi[app_config.avi_def_idx].dev_id != PJMEDIA_VID_INVALID_DEV)
-    {
-	acc_cfg->vid_cap_dev = app_config.avi[app_config.avi_def_idx].dev_id;
-    }
-}
-#else
-PJ_DEF(void) app_config_init_video(pjsua_acc_config *acc_cfg)
-{
-    PJ_UNUSED_ARG(acc_cfg);
-}
-#endif
-
-#ifdef HAVE_MULTIPART_TEST
-  /*
-   * Enable multipart in msg_data and add a dummy body into the
-   * multipart bodies.
-   */
-  PJ_DEF(void) add_multipart(pjsua_msg_data *msg_data)
-  {
-      static pjsip_multipart_part *alt_part;
-
-      if (!alt_part) {
-	  pj_str_t type, subtype, content;
-
-	  alt_part = pjsip_multipart_create_part(app_config.pool);
-
-	  type = pj_str("text");
-	  subtype = pj_str("plain");
-	  content = pj_str("Sample text body of a multipart bodies");
-	  alt_part->body = pjsip_msg_body_create(app_config.pool, &type,
-						 &subtype, &content);
-      }
-
-      msg_data->multipart_ctype.type = pj_str("multipart");
-      msg_data->multipart_ctype.subtype = pj_str("mixed");
-      pj_list_push_back(&msg_data->multipart_parts, alt_part);
-  }
-#endif
-
-/* arrange windows. arg:
- *   -1:    arrange all windows
- *   != -1: arrange only this window id
- */
-PJ_DEF(void) arrange_window(pjsua_vid_win_id wid)
-{
-#if PJSUA_HAS_VIDEO
-    pjmedia_coord pos;
-    int i, last;
-
-    pos.x = 0;
-    pos.y = 10;
-    last = (wid == PJSUA_INVALID_ID) ? PJSUA_MAX_VID_WINS : wid;
-
-    for (i=0; i<last; ++i) {
-	pjsua_vid_win_info wi;
-	pj_status_t status;
-
-	status = pjsua_vid_win_get_info(i, &wi);
-	if (status != PJ_SUCCESS)
-	    continue;
-
-	if (wid == PJSUA_INVALID_ID)
-	    pjsua_vid_win_set_pos(i, &pos);
-
-	if (wi.show)
-	    pos.y += wi.size.h;
-    }
-
-    if (wid != PJSUA_INVALID_ID)
-	pjsua_vid_win_set_pos(wid, &pos);
-#else
-    PJ_UNUSED_ARG(wid);
-#endif
-}
-
-
-#if PJSUA_HAS_VIDEO
-PJ_DEF(void) vid_print_dev(int id, const pjmedia_vid_dev_info *vdi,
-                          const char *title)
-{
-    char capnames[120];
-    char formats[120];
-    const char *dirname;
-    unsigned i;
-
-    if (vdi->dir == PJMEDIA_DIR_CAPTURE_RENDER) {
-	dirname = "capture, render";
-    } else if (vdi->dir == PJMEDIA_DIR_CAPTURE) {
-	dirname = "capture";
-    } else {
-	dirname = "render";
-    }
-
-
-    capnames[0] = '\0';
-    for (i=0; i<sizeof(int)*8 && (1 << i) < PJMEDIA_VID_DEV_CAP_MAX; ++i) {
-	if (vdi->caps & (1 << i)) {
-	    const char *capname = pjmedia_vid_dev_cap_name(1 << i, NULL);
-	    if (capname) {
-		if (*capnames)
-		    strcat(capnames, ", ");
-		strncat(capnames, capname,
-		        sizeof(capnames)-strlen(capnames)-1);
-	    }
-	}
-    }
-
-    formats[0] = '\0';
-    for (i=0; i<vdi->fmt_cnt; ++i) {
-	const pjmedia_video_format_info *vfi =
-		pjmedia_get_video_format_info(NULL, vdi->fmt[i].id);
-	if (vfi) {
-	    if (*formats)
-		strcat(formats, ", ");
-	    strncat(formats, vfi->name, sizeof(formats)-strlen(formats)-1);
-	}
-    }
-
-    PJ_LOG(3,(THIS_FILE, "%3d %s [%s][%s] %s", id, vdi->name, vdi->driver,
-	      dirname, title));
-    PJ_LOG(3,(THIS_FILE, "    Supported capabilities: %s", capnames));
-    PJ_LOG(3,(THIS_FILE, "    Supported formats: %s", formats));
-}
-
-PJ_DEF(void) vid_list_devs()
-{
-    unsigned i, count;
-    pjmedia_vid_dev_info vdi;
-    pj_status_t status;
-
-    PJ_LOG(3,(THIS_FILE, "Video device list:"));
-    count = pjsua_vid_dev_count();
-    if (count == 0) {
-	PJ_LOG(3,(THIS_FILE, " - no device detected -"));
-	return;
-    } else {
-	PJ_LOG(3,(THIS_FILE, "%d device(s) detected:", count));
-    }
-
-    status = pjsua_vid_dev_get_info(PJMEDIA_VID_DEFAULT_RENDER_DEV, &vdi);
-    if (status == PJ_SUCCESS)
-	vid_print_dev(PJMEDIA_VID_DEFAULT_RENDER_DEV, &vdi,
-	              "(default renderer device)");
-
-    status = pjsua_vid_dev_get_info(PJMEDIA_VID_DEFAULT_CAPTURE_DEV, &vdi);
-    if (status == PJ_SUCCESS)
-	vid_print_dev(PJMEDIA_VID_DEFAULT_CAPTURE_DEV, &vdi,
-	              "(default capture device)");
-
-    for (i=0; i<count; ++i) {
-	status = pjsua_vid_dev_get_info(i, &vdi);
-	if (status == PJ_SUCCESS)
-	    vid_print_dev(i, &vdi, "");
-    }
-}
-
-PJ_DEF(void) app_config_show_video(int acc_id, const pjsua_acc_config *acc_cfg)
-{
-    PJ_LOG(3,(THIS_FILE,
-	      "Account %d:\n"
-	      "  RX auto show:     %d\n"
-	      "  TX auto transmit: %d\n"
-	      "  Capture dev:      %d\n"
-	      "  Render dev:       %d",
-	      acc_id,
-	      acc_cfg->vid_in_auto_show,
-	      acc_cfg->vid_out_auto_transmit,
-	      acc_cfg->vid_cap_dev,
-	      acc_cfg->vid_rend_dev));
-}
-
-
-#endif
-
Index: project/trunk/pjsip-apps/src/pjsua/pjsua_cmd.h
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_cmd.h	(revision 4460)
+++ 	(revision )
@@ -1,180 +1,0 @@
-/* $Id$ */
-/* 
- * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
- */
-#ifndef __PJSUA_CMD_H__
-#define __PJSUA_CMD_H__
-
-#include <pjsua-lib/pjsua.h>
-
-PJ_BEGIN_DECL
-
-#define current_acc	pjsua_acc_get_default()
-
-#define NO_LIMIT_DURATION   (int)0x7FFFFFFF
-#define MAX_AVI		    4
-#define NO_NB		    -2
-
-typedef struct input_result
-{
-    int	  nb_result;
-    char *uri_result;
-} input_result;
-
-/* Call specific data */
-typedef struct call_data
-{
-    pj_timer_entry	    timer;
-    pj_bool_t		    ringback_on;
-    pj_bool_t		    ring_on;
-} call_data;
-
-/* Video settings */
-typedef struct app_vid
-{
-    unsigned		    vid_cnt;
-    int			    vcapture_dev;
-    int			    vrender_dev;
-    pj_bool_t		    in_auto_show;
-    pj_bool_t		    out_auto_transmit;
-} app_vid;
-
-/* Pjsua application data */
-typedef struct pjsua_app_config
-{
-    pjsua_config	    cfg;
-    pjsua_logging_config    log_cfg;
-    pjsua_media_config	    media_cfg;
-    pj_bool_t		    no_refersub;
-    pj_bool_t		    ipv6;
-    pj_bool_t		    enable_qos;
-    pj_bool_t		    no_tcp;
-    pj_bool_t		    no_udp;
-    pj_bool_t		    use_tls;
-    pjsua_transport_config  udp_cfg;
-    pjsua_transport_config  rtp_cfg;
-    pjsip_redirect_op	    redir_op;
-
-    unsigned		    acc_cnt;
-    pjsua_acc_config	    acc_cfg[PJSUA_MAX_ACC];
-
-    unsigned		    buddy_cnt;
-    pjsua_buddy_config	    buddy_cfg[PJSUA_MAX_BUDDIES];
-
-    call_data		    call_data[PJSUA_MAX_CALLS];
-
-    pj_pool_t		   *pool;
-    /* Compatibility with older pjsua */
-
-    unsigned		    codec_cnt;
-    pj_str_t		    codec_arg[32];
-    unsigned		    codec_dis_cnt;
-    pj_str_t                codec_dis[32];
-    pj_bool_t		    null_audio;
-    unsigned		    wav_count;
-    pj_str_t		    wav_files[32];
-    unsigned		    tone_count;
-    pjmedia_tone_desc	    tones[32];
-    pjsua_conf_port_id	    tone_slots[32];
-    pjsua_player_id	    wav_id;
-    pjsua_conf_port_id	    wav_port;
-    pj_bool_t		    auto_play;
-    pj_bool_t		    auto_play_hangup;
-    pj_timer_entry	    auto_hangup_timer;
-    pj_bool_t		    auto_loop;
-    pj_bool_t		    auto_conf;
-    pj_str_t		    rec_file;
-    pj_bool_t		    auto_rec;
-    pjsua_recorder_id	    rec_id;
-    pjsua_conf_port_id	    rec_port;
-    unsigned		    auto_answer;
-    unsigned		    duration;
-
-#ifdef STEREO_DEMO
-    pjmedia_snd_port	   *snd;
-    pjmedia_port	   *sc, *sc_ch1;
-    pjsua_conf_port_id	    sc_ch1_slot;
-#endif
-
-    float		    mic_level,
-			    speaker_level;
-
-    int			    capture_dev, playback_dev;
-    unsigned		    capture_lat, playback_lat;
-
-    pj_bool_t		    no_tones;
-    int			    ringback_slot;
-    int			    ringback_cnt;
-    pjmedia_port	   *ringback_port;
-    int			    ring_slot;
-    int			    ring_cnt;
-    pjmedia_port	   *ring_port;
-
-    app_vid		    vid;
-    unsigned		    aud_cnt;
-
-    /* AVI to play */
-    unsigned                avi_cnt;
-    struct {
-	pj_str_t		path;
-	pjmedia_vid_dev_index	dev_id;
-	pjsua_conf_port_id	slot;
-    } avi[MAX_AVI];
-    pj_bool_t               avi_auto_play;
-    int			    avi_def_idx;
-
-    /* CLI setting */
-    pj_bool_t		    use_cli;
-    unsigned		    cli_telnet_port;    
-} pjsua_app_config;
-
-/** Extern variable declaration **/
-extern pjsua_call_id	    current_call;
-extern pjsua_app_config	    app_config;
-extern int		    stdout_refresh;
-extern pj_bool_t	    stdout_refresh_quit;
-extern pjsua_call_setting call_opt;
-extern pjsua_msg_data msg_data;
-
-PJ_DECL(int) my_atoi(const char *cs);
-PJ_DECL(pj_bool_t) find_next_call();
-PJ_DECL(pj_bool_t) find_prev_call();
-PJ_DECL(void) send_request(char *cstr_method, const pj_str_t *dst_uri);
-PJ_DECL(void) log_call_dump(int call_id);
-PJ_DECL(int) write_settings(pjsua_app_config *cfg, char *buf, pj_size_t max);
-PJ_DECL(void) app_config_init_video(pjsua_acc_config *acc_cfg);
-PJ_DECL(void) arrange_window(pjsua_vid_win_id wid);
-
-#if PJSUA_HAS_VIDEO
-PJ_DECL(void) vid_print_dev(int id, const pjmedia_vid_dev_info *vdi, const char *title);
-PJ_DECL(void) vid_list_devs();
-PJ_DECL(void) app_config_show_video(int acc_id, const pjsua_acc_config *acc_cfg);
-#endif
-
-#ifdef HAVE_MULTIPART_TEST
-    /*
-    * Enable multipart in msg_data and add a dummy body into the
-    * multipart bodies.
-    */
-    PJ_DECL(void) add_multipart(pjsua_msg_data *msg_data);
-#  define TEST_MULTIPART(msg_data)	add_multipart(msg_data)
-#else
-#  define TEST_MULTIPART(msg_data)
-#endif
-
-#endif	/* __PJSUA_CMD_H__ */
-
Index: /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_common.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_common.c	(revision 4461)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_common.c	(revision 4461)
@@ -0,0 +1,356 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
+ * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.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 
+ */
+
+#include "pjsua_common.h"
+
+#define THIS_FILE	"pjsua_common.c"
+
+#if defined(PJMEDIA_HAS_RTCP_XR) && (PJMEDIA_HAS_RTCP_XR != 0)
+#   define SOME_BUF_SIZE	(1024 * 10)
+#else
+#   define SOME_BUF_SIZE	(1024 * 3)
+#endif
+
+static char some_buf[SOME_BUF_SIZE];
+
+/** Variable definition **/
+int		    stdout_refresh = -1;
+pj_bool_t	    stdout_refresh_quit = PJ_FALSE;
+pjsua_call_id	    current_call = PJSUA_INVALID_ID;
+pjsua_app_config    app_config;
+pjsua_call_setting  call_opt;
+pjsua_msg_data	    msg_data;
+
+PJ_DEF(int) my_atoi(const char *cs)
+{
+    pj_str_t s;
+
+    pj_cstr(&s, cs);
+    if (cs[0] == '-') {
+	s.ptr++, s.slen--;
+	return 0 - (int)pj_strtoul(&s);
+    } else if (cs[0] == '+') {
+	s.ptr++, s.slen--;
+	return pj_strtoul(&s);
+    } else {
+	return pj_strtoul(&s);
+    }
+}
+
+/*
+ * Find next call when current call is disconnected or when user
+ * press ']'
+ */
+PJ_DEF(pj_bool_t) find_next_call()
+{
+    int i, max;
+
+    max = pjsua_call_get_max_count();
+    for (i=current_call+1; i<max; ++i) {
+	if (pjsua_call_is_active(i)) {
+	    current_call = i;
+	    return PJ_TRUE;
+	}
+    }
+
+    for (i=0; i<current_call; ++i) {
+	if (pjsua_call_is_active(i)) {
+	    current_call = i;
+	    return PJ_TRUE;
+	}
+    }
+
+    current_call = PJSUA_INVALID_ID;
+    return PJ_FALSE;
+}
+
+PJ_DEF(pj_bool_t) find_prev_call()
+{
+    int i, max;
+
+    max = pjsua_call_get_max_count();
+    for (i=current_call-1; i>=0; --i) {
+	if (pjsua_call_is_active(i)) {
+	    current_call = i;
+	    return PJ_TRUE;
+	}
+    }
+
+    for (i=max-1; i>current_call; --i) {
+	if (pjsua_call_is_active(i)) {
+	    current_call = i;
+	    return PJ_TRUE;
+	}
+    }
+
+    current_call = PJSUA_INVALID_ID;
+    return PJ_FALSE;
+}
+
+/*
+ * Send arbitrary request to remote host
+ */
+PJ_DEF(void) send_request(char *cstr_method, const pj_str_t *dst_uri)
+{
+    pj_str_t str_method;
+    pjsip_method method;
+    pjsip_tx_data *tdata;
+    pjsip_endpoint *endpt;
+    pj_status_t status;
+
+    endpt = pjsua_get_pjsip_endpt();
+
+    str_method = pj_str(cstr_method);
+    pjsip_method_init_np(&method, &str_method);
+
+    status = pjsua_acc_create_request(current_acc, &method, dst_uri, &tdata);
+
+    status = pjsip_endpt_send_request(endpt, tdata, -1, NULL, NULL);
+    if (status != PJ_SUCCESS) {
+	pjsua_perror(THIS_FILE, "Unable to send request", status);
+	return;
+    }
+}
+
+/*
+ * Print log of call states. Since call states may be too long for logger,
+ * printing it is a bit tricky, it should be printed part by part as long 
+ * as the logger can accept.
+ */
+PJ_DEF(void) log_call_dump(int call_id) 
+{
+    unsigned call_dump_len;
+    unsigned part_len;
+    unsigned part_idx;
+    unsigned log_decor;
+
+    pjsua_call_dump(call_id, PJ_TRUE, some_buf, sizeof(some_buf), "  ");
+    call_dump_len = strlen(some_buf);
+
+    log_decor = pj_log_get_decor();
+    pj_log_set_decor(log_decor & ~(PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_CR));
+    PJ_LOG(3,(THIS_FILE, "\n"));
+    pj_log_set_decor(0);
+
+    part_idx = 0;
+    part_len = PJ_LOG_MAX_SIZE-80;
+    while (part_idx < call_dump_len) {
+	char p_orig, *p;
+
+	p = &some_buf[part_idx];
+	if (part_idx + part_len > call_dump_len)
+	    part_len = call_dump_len - part_idx;
+	p_orig = p[part_len];
+	p[part_len] = '\0';
+	PJ_LOG(3,(THIS_FILE, "%s", p));
+	p[part_len] = p_orig;
+	part_idx += part_len;
+    }
+    pj_log_set_decor(log_decor);
+}
+
+#ifdef PJSUA_HAS_VIDEO
+PJ_DEF(void) app_config_init_video(pjsua_acc_config *acc_cfg)
+{
+    acc_cfg->vid_in_auto_show = app_config.vid.in_auto_show;
+    acc_cfg->vid_out_auto_transmit = app_config.vid.out_auto_transmit;
+    /* Note that normally GUI application will prefer a borderless
+     * window.
+     */
+    acc_cfg->vid_wnd_flags = PJMEDIA_VID_DEV_WND_BORDER |
+                             PJMEDIA_VID_DEV_WND_RESIZABLE;
+    acc_cfg->vid_cap_dev = app_config.vid.vcapture_dev;
+    acc_cfg->vid_rend_dev = app_config.vid.vrender_dev;
+
+    if (app_config.avi_auto_play &&
+	app_config.avi_def_idx != PJSUA_INVALID_ID &&
+	app_config.avi[app_config.avi_def_idx].dev_id != PJMEDIA_VID_INVALID_DEV)
+    {
+	acc_cfg->vid_cap_dev = app_config.avi[app_config.avi_def_idx].dev_id;
+    }
+}
+#else
+PJ_DEF(void) app_config_init_video(pjsua_acc_config *acc_cfg)
+{
+    PJ_UNUSED_ARG(acc_cfg);
+}
+#endif
+
+#ifdef HAVE_MULTIPART_TEST
+  /*
+   * Enable multipart in msg_data and add a dummy body into the
+   * multipart bodies.
+   */
+  PJ_DEF(void) add_multipart(pjsua_msg_data *msg_data)
+  {
+      static pjsip_multipart_part *alt_part;
+
+      if (!alt_part) {
+	  pj_str_t type, subtype, content;
+
+	  alt_part = pjsip_multipart_create_part(app_config.pool);
+
+	  type = pj_str("text");
+	  subtype = pj_str("plain");
+	  content = pj_str("Sample text body of a multipart bodies");
+	  alt_part->body = pjsip_msg_body_create(app_config.pool, &type,
+						 &subtype, &content);
+      }
+
+      msg_data->multipart_ctype.type = pj_str("multipart");
+      msg_data->multipart_ctype.subtype = pj_str("mixed");
+      pj_list_push_back(&msg_data->multipart_parts, alt_part);
+  }
+#endif
+
+/* arrange windows. arg:
+ *   -1:    arrange all windows
+ *   != -1: arrange only this window id
+ */
+PJ_DEF(void) arrange_window(pjsua_vid_win_id wid)
+{
+#if PJSUA_HAS_VIDEO
+    pjmedia_coord pos;
+    int i, last;
+
+    pos.x = 0;
+    pos.y = 10;
+    last = (wid == PJSUA_INVALID_ID) ? PJSUA_MAX_VID_WINS : wid;
+
+    for (i=0; i<last; ++i) {
+	pjsua_vid_win_info wi;
+	pj_status_t status;
+
+	status = pjsua_vid_win_get_info(i, &wi);
+	if (status != PJ_SUCCESS)
+	    continue;
+
+	if (wid == PJSUA_INVALID_ID)
+	    pjsua_vid_win_set_pos(i, &pos);
+
+	if (wi.show)
+	    pos.y += wi.size.h;
+    }
+
+    if (wid != PJSUA_INVALID_ID)
+	pjsua_vid_win_set_pos(wid, &pos);
+#else
+    PJ_UNUSED_ARG(wid);
+#endif
+}
+
+
+#if PJSUA_HAS_VIDEO
+PJ_DEF(void) vid_print_dev(int id, const pjmedia_vid_dev_info *vdi,
+                          const char *title)
+{
+    char capnames[120];
+    char formats[120];
+    const char *dirname;
+    unsigned i;
+
+    if (vdi->dir == PJMEDIA_DIR_CAPTURE_RENDER) {
+	dirname = "capture, render";
+    } else if (vdi->dir == PJMEDIA_DIR_CAPTURE) {
+	dirname = "capture";
+    } else {
+	dirname = "render";
+    }
+
+
+    capnames[0] = '\0';
+    for (i=0; i<sizeof(int)*8 && (1 << i) < PJMEDIA_VID_DEV_CAP_MAX; ++i) {
+	if (vdi->caps & (1 << i)) {
+	    const char *capname = pjmedia_vid_dev_cap_name(1 << i, NULL);
+	    if (capname) {
+		if (*capnames)
+		    strcat(capnames, ", ");
+		strncat(capnames, capname,
+		        sizeof(capnames)-strlen(capnames)-1);
+	    }
+	}
+    }
+
+    formats[0] = '\0';
+    for (i=0; i<vdi->fmt_cnt; ++i) {
+	const pjmedia_video_format_info *vfi =
+		pjmedia_get_video_format_info(NULL, vdi->fmt[i].id);
+	if (vfi) {
+	    if (*formats)
+		strcat(formats, ", ");
+	    strncat(formats, vfi->name, sizeof(formats)-strlen(formats)-1);
+	}
+    }
+
+    PJ_LOG(3,(THIS_FILE, "%3d %s [%s][%s] %s", id, vdi->name, vdi->driver,
+	      dirname, title));
+    PJ_LOG(3,(THIS_FILE, "    Supported capabilities: %s", capnames));
+    PJ_LOG(3,(THIS_FILE, "    Supported formats: %s", formats));
+}
+
+PJ_DEF(void) vid_list_devs()
+{
+    unsigned i, count;
+    pjmedia_vid_dev_info vdi;
+    pj_status_t status;
+
+    PJ_LOG(3,(THIS_FILE, "Video device list:"));
+    count = pjsua_vid_dev_count();
+    if (count == 0) {
+	PJ_LOG(3,(THIS_FILE, " - no device detected -"));
+	return;
+    } else {
+	PJ_LOG(3,(THIS_FILE, "%d device(s) detected:", count));
+    }
+
+    status = pjsua_vid_dev_get_info(PJMEDIA_VID_DEFAULT_RENDER_DEV, &vdi);
+    if (status == PJ_SUCCESS)
+	vid_print_dev(PJMEDIA_VID_DEFAULT_RENDER_DEV, &vdi,
+	              "(default renderer device)");
+
+    status = pjsua_vid_dev_get_info(PJMEDIA_VID_DEFAULT_CAPTURE_DEV, &vdi);
+    if (status == PJ_SUCCESS)
+	vid_print_dev(PJMEDIA_VID_DEFAULT_CAPTURE_DEV, &vdi,
+	              "(default capture device)");
+
+    for (i=0; i<count; ++i) {
+	status = pjsua_vid_dev_get_info(i, &vdi);
+	if (status == PJ_SUCCESS)
+	    vid_print_dev(i, &vdi, "");
+    }
+}
+
+PJ_DEF(void) app_config_show_video(int acc_id, const pjsua_acc_config *acc_cfg)
+{
+    PJ_LOG(3,(THIS_FILE,
+	      "Account %d:\n"
+	      "  RX auto show:     %d\n"
+	      "  TX auto transmit: %d\n"
+	      "  Capture dev:      %d\n"
+	      "  Render dev:       %d",
+	      acc_id,
+	      acc_cfg->vid_in_auto_show,
+	      acc_cfg->vid_out_auto_transmit,
+	      acc_cfg->vid_cap_dev,
+	      acc_cfg->vid_rend_dev));
+}
+
+
+#endif
Index: /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_common.h
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_common.h	(revision 4461)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_common.h	(revision 4461)
@@ -0,0 +1,214 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
+ */
+#ifndef __PJSUA_COMMON_H__
+#define __PJSUA_COMMON_H__
+
+#include <pjsua-lib/pjsua.h>
+
+PJ_BEGIN_DECL
+
+#define current_acc	pjsua_acc_get_default()
+
+#define NO_LIMIT_DURATION   (int)0x7FFFFFFF
+#define MAX_AVI		    4
+#define NO_NB		    -2
+
+typedef struct input_result
+{
+    int	  nb_result;
+    char *uri_result;
+} input_result;
+
+/* Call specific data */
+typedef struct app_call_data
+{
+    pj_timer_entry	    timer;
+    pj_bool_t		    ringback_on;
+    pj_bool_t		    ring_on;
+} app_call_data;
+
+/* Video settings */
+typedef struct app_vid
+{
+    unsigned		    vid_cnt;
+    int			    vcapture_dev;
+    int			    vrender_dev;
+    pj_bool_t		    in_auto_show;
+    pj_bool_t		    out_auto_transmit;
+} app_vid;
+
+/* Pjsua application data */
+typedef struct pjsua_app_config
+{
+    pjsua_config	    cfg;
+    pjsua_logging_config    log_cfg;
+    pjsua_media_config	    media_cfg;
+    pj_bool_t		    no_refersub;
+    pj_bool_t		    ipv6;
+    pj_bool_t		    enable_qos;
+    pj_bool_t		    no_tcp;
+    pj_bool_t		    no_udp;
+    pj_bool_t		    use_tls;
+    pjsua_transport_config  udp_cfg;
+    pjsua_transport_config  rtp_cfg;
+    pjsip_redirect_op	    redir_op;
+
+    unsigned		    acc_cnt;
+    pjsua_acc_config	    acc_cfg[PJSUA_MAX_ACC];
+
+    unsigned		    buddy_cnt;
+    pjsua_buddy_config	    buddy_cfg[PJSUA_MAX_BUDDIES];
+
+    app_call_data	    call_data[PJSUA_MAX_CALLS];
+
+    pj_pool_t		   *pool;
+    /* Compatibility with older pjsua */
+
+    unsigned		    codec_cnt;
+    pj_str_t		    codec_arg[32];
+    unsigned		    codec_dis_cnt;
+    pj_str_t                codec_dis[32];
+    pj_bool_t		    null_audio;
+    unsigned		    wav_count;
+    pj_str_t		    wav_files[32];
+    unsigned		    tone_count;
+    pjmedia_tone_desc	    tones[32];
+    pjsua_conf_port_id	    tone_slots[32];
+    pjsua_player_id	    wav_id;
+    pjsua_conf_port_id	    wav_port;
+    pj_bool_t		    auto_play;
+    pj_bool_t		    auto_play_hangup;
+    pj_timer_entry	    auto_hangup_timer;
+    pj_bool_t		    auto_loop;
+    pj_bool_t		    auto_conf;
+    pj_str_t		    rec_file;
+    pj_bool_t		    auto_rec;
+    pjsua_recorder_id	    rec_id;
+    pjsua_conf_port_id	    rec_port;
+    unsigned		    auto_answer;
+    unsigned		    duration;
+
+#ifdef STEREO_DEMO
+    pjmedia_snd_port	   *snd;
+    pjmedia_port	   *sc, *sc_ch1;
+    pjsua_conf_port_id	    sc_ch1_slot;
+#endif
+
+    float		    mic_level,
+			    speaker_level;
+
+    int			    capture_dev, playback_dev;
+    unsigned		    capture_lat, playback_lat;
+
+    pj_bool_t		    no_tones;
+    int			    ringback_slot;
+    int			    ringback_cnt;
+    pjmedia_port	   *ringback_port;
+    int			    ring_slot;
+    int			    ring_cnt;
+    pjmedia_port	   *ring_port;
+
+    app_vid		    vid;
+    unsigned		    aud_cnt;
+
+    /* AVI to play */
+    unsigned                avi_cnt;
+    struct {
+	pj_str_t		path;
+	pjmedia_vid_dev_index	dev_id;
+	pjsua_conf_port_id	slot;
+    } avi[MAX_AVI];
+    pj_bool_t               avi_auto_play;
+    int			    avi_def_idx;
+
+    /* CLI setting */
+    pj_bool_t		    use_cli;
+    int			    cli_telnet_port;
+    pj_bool_t		    disable_cli_console;
+} pjsua_app_config;
+
+/** CLI callback **/
+/** This specifies the callback called when cli quit is called. **/
+typedef void (*pj_cli_on_quit)(pj_bool_t is_restarting);
+/** This callback is called when the cli is completely destroyed **/
+typedef void (*pj_cli_on_destroy)(void);
+/** This callback is called when pjsua restart command is invode by cli **/
+typedef void (*pj_cli_on_restart_pjsua)(void);
+
+/** Extern variable declaration **/
+extern pjsua_call_id	    current_call;
+extern pjsua_app_config	    app_config;
+extern int		    stdout_refresh;
+extern pj_bool_t	    stdout_refresh_quit;
+extern pjsua_call_setting   call_opt;
+extern pjsua_msg_data	    msg_data;
+
+PJ_DECL(int) my_atoi(const char *cs);
+PJ_DECL(pj_bool_t) find_next_call();
+PJ_DECL(pj_bool_t) find_prev_call();
+PJ_DECL(void) send_request(char *cstr_method, const pj_str_t *dst_uri);
+PJ_DECL(void) log_call_dump(int call_id);
+PJ_DECL(int) write_settings(pjsua_app_config *cfg, char *buf, pj_size_t max);
+PJ_DECL(void) app_config_init_video(pjsua_acc_config *acc_cfg);
+PJ_DECL(void) arrange_window(pjsua_vid_win_id wid);
+
+/** Defined in pjsua_cli_cmd.c **/
+PJ_DECL(pj_bool_t) is_cli_inited();
+
+/** Defined in pjsua_app.c **/
+PJ_DECL(pj_status_t) app_init(pj_cli_telnet_on_started on_started_cb,
+			      pj_cli_on_quit on_quit_cb,
+			      pj_cli_on_destroy on_destroy_cb,
+			      pj_cli_on_restart_pjsua on_restart_pjsua_cb);
+PJ_DECL(void) setup_signal_handler(void);
+
+/** Defined in pjsua_config.c **/
+/** This is to store the app runtime/startup options **/
+PJ_DECL(void) add_startup_config(int argc, char *argv[]);
+/** This is to store the app reload options **/
+PJ_DECL(void) add_reload_config(unsigned idx, pj_str_t *option);
+/** This is to load the configuration **/
+PJ_DECL(pj_status_t) load_config(pjsua_app_config *app_config, 
+				 pj_str_t *uri_arg,
+				 pj_bool_t app_running);
+
+#if PJSUA_HAS_VIDEO
+PJ_DECL(void) vid_print_dev(int id, const pjmedia_vid_dev_info *vdi, 
+			    const char *title);
+PJ_DECL(void) vid_list_devs();
+PJ_DECL(void) app_config_show_video(int acc_id, 
+				    const pjsua_acc_config *acc_cfg);
+#endif
+
+#ifdef HAVE_MULTIPART_TEST
+    /*
+    * Enable multipart in msg_data and add a dummy body into the
+    * multipart bodies.
+    */
+    PJ_DECL(void) add_multipart(pjsua_msg_data *msg_data);
+#  define TEST_MULTIPART(msg_data)	add_multipart(msg_data)
+#else
+#  define TEST_MULTIPART(msg_data)
+#endif
+
+
+PJ_END_DECL
+    
+#endif	/* __PJSUA_CMD_H__ */
+
Index: /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_config.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_config.c	(revision 4461)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_config.c	(revision 4461)
@@ -0,0 +1,2213 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
+ * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.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 
+ */
+#include <pjsua-lib/pjsua.h>
+#include "pjsua_common.h"
+
+#define THIS_FILE	"pjsua_config.c"
+
+#define MAX_APP_OPTIONS 128
+
+char   *stdout_refresh_text = "STDOUT_REFRESH";
+
+/** This is for storing console runtime options **/
+static int	    cmd_argc;
+static char	    cmd_argv[MAX_APP_OPTIONS][MAX_APP_OPTIONS];
+
+/* Show usage */
+static void usage(void)
+{
+    puts  ("Usage:");
+    puts  ("  pjsua [options] [SIP URL to call]");
+    puts  ("");
+    puts  ("General options:");
+    puts  ("  --config-file=file  Read the config/arguments from file.");
+    puts  ("  --help              Display this help screen");
+    puts  ("  --version           Display version info");
+    puts  ("");
+    puts  ("Logging options:");
+    puts  ("  --log-file=fname    Log to filename (default stderr)");
+    puts  ("  --log-level=N       Set log max level to N (0(none) to 6(trace)) (default=5)");
+    puts  ("  --app-log-level=N   Set log max level for stdout display (default=4)");
+    puts  ("  --log-append        Append instead of overwrite existing log file.\n");
+    puts  ("  --color             Use colorful logging (default yes on Win32)");
+    puts  ("  --no-color          Disable colorful logging");
+    puts  ("  --light-bg          Use dark colors for light background (default is dark bg)");
+    puts  ("  --no-stderr         Disable stderr");
+
+    puts  ("");
+    puts  ("SIP Account options:");
+    puts  ("  --registrar=url     Set the URL of registrar server");
+    puts  ("  --id=url            Set the URL of local ID (used in From header)");
+    puts  ("  --realm=string      Set realm");
+    puts  ("  --username=string   Set authentication username");
+    puts  ("  --password=string   Set authentication password");
+    puts  ("  --contact=url       Optionally override the Contact information");
+    puts  ("  --contact-params=S  Append the specified parameters S in Contact header");
+    puts  ("  --contact-uri-params=S  Append the specified parameters S in Contact URI");
+    puts  ("  --proxy=url         Optional URL of proxy server to visit");
+    puts  ("                      May be specified multiple times");
+    printf("  --reg-timeout=SEC   Optional registration interval (default %d)\n",
+	    PJSUA_REG_INTERVAL);
+    printf("  --rereg-delay=SEC   Optional auto retry registration interval (default %d)\n",
+	    PJSUA_REG_RETRY_INTERVAL);
+    puts  ("  --reg-use-proxy=N   Control the use of proxy settings in REGISTER.");
+    puts  ("                      0=no proxy, 1=outbound only, 2=acc only, 3=all (default)");
+    puts  ("  --publish           Send presence PUBLISH for this account");
+    puts  ("  --mwi               Subscribe to message summary/waiting indication");
+    puts  ("  --use-ims           Enable 3GPP/IMS related settings on this account");
+#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
+    puts  ("  --use-srtp=N        Use SRTP?  0:disabled, 1:optional, 2:mandatory,");
+    puts  ("                      3:optional by duplicating media offer (def:0)");
+    puts  ("  --srtp-secure=N     SRTP require secure SIP? 0:no, 1:tls, 2:sips (def:1)");
+#endif
+    puts  ("  --use-100rel        Require reliable provisional response (100rel)");
+    puts  ("  --use-timer=N       Use SIP session timers? (default=1)");
+    puts  ("                      0:inactive, 1:optional, 2:mandatory, 3:always");
+    printf("  --timer-se=N        Session timers expiration period, in secs (def:%d)\n",
+	    PJSIP_SESS_TIMER_DEF_SE);
+    puts  ("  --timer-min-se=N    Session timers minimum expiration period, in secs (def:90)");
+    puts  ("  --outb-rid=string   Set SIP outbound reg-id (default:1)");
+    puts  ("  --auto-update-nat=N Where N is 0 or 1 to enable/disable SIP traversal behind");
+    puts  ("                      symmetric NAT (default 1)");
+    puts  ("  --disable-stun      Disable STUN for this account");
+    puts  ("  --next-cred         Add another credentials");
+    puts  ("");
+    puts  ("SIP Account Control:");
+    puts  ("  --next-account      Add more account");
+    puts  ("");
+    puts  ("Transport Options:");
+#if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6
+    puts  ("  --ipv6              Use IPv6 instead for SIP and media.");
+#endif
+    puts  ("  --set-qos           Enable QoS tagging for SIP and media.");
+    puts  ("  --local-port=port   Set TCP/UDP port. This implicitly enables both ");
+    puts  ("                      TCP and UDP transports on the specified port, unless");
+    puts  ("                      if TCP or UDP is disabled.");
+    puts  ("  --ip-addr=IP        Use the specifed address as SIP and RTP addresses.");
+    puts  ("                      (Hint: the IP may be the public IP of the NAT/router)");
+    puts  ("  --bound-addr=IP     Bind transports to this IP interface");
+    puts  ("  --no-tcp            Disable TCP transport.");
+    puts  ("  --no-udp            Disable UDP transport.");
+    puts  ("  --nameserver=NS     Add the specified nameserver to enable SRV resolution");
+    puts  ("                      This option can be specified multiple times.");
+    puts  ("  --outbound=url      Set the URL of global outbound proxy server");
+    puts  ("                      May be specified multiple times");
+    puts  ("  --stun-srv=FORMAT   Set STUN server host or domain. This option may be");
+    puts  ("                      specified more than once. FORMAT is hostdom[:PORT]");
+
+#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
+    puts  ("");
+    puts  ("TLS Options:");
+    puts  ("  --use-tls           Enable TLS transport (default=no)");
+    puts  ("  --tls-ca-file       Specify TLS CA file (default=none)");
+    puts  ("  --tls-cert-file     Specify TLS certificate file (default=none)");
+    puts  ("  --tls-privkey-file  Specify TLS private key file (default=none)");
+    puts  ("  --tls-password      Specify TLS password to private key file (default=none)");
+    puts  ("  --tls-verify-server Verify server's certificate (default=no)");
+    puts  ("  --tls-verify-client Verify client's certificate (default=no)");
+    puts  ("  --tls-neg-timeout   Specify TLS negotiation timeout (default=no)");
+    puts  ("  --tls-srv-name      Specify TLS server name for multihosting server");
+    puts  ("  --tls-cipher        Specify prefered TLS cipher (optional).");
+    puts  ("                      May be specified multiple times");
+#endif
+
+    puts  ("");
+    puts  ("Audio Options:");
+    puts  ("  --add-codec=name    Manually add codec (default is to enable all)");
+    puts  ("  --dis-codec=name    Disable codec (can be specified multiple times)");
+    puts  ("  --clock-rate=N      Override conference bridge clock rate");
+    puts  ("  --snd-clock-rate=N  Override sound device clock rate");
+    puts  ("  --stereo            Audio device and conference bridge opened in stereo mode");
+    puts  ("  --null-audio        Use NULL audio device");
+    puts  ("  --play-file=file    Register WAV file in conference bridge.");
+    puts  ("                      This can be specified multiple times.");
+    puts  ("  --play-tone=FORMAT  Register tone to the conference bridge.");
+    puts  ("                      FORMAT is 'F1,F2,ON,OFF', where F1,F2 are");
+    puts  ("                      frequencies, and ON,OFF=on/off duration in msec.");
+    puts  ("                      This can be specified multiple times.");
+    puts  ("  --auto-play         Automatically play the file (to incoming calls only)");
+    puts  ("  --auto-loop         Automatically loop incoming RTP to outgoing RTP");
+    puts  ("  --auto-conf         Automatically put calls in conference with others");
+    puts  ("  --rec-file=file     Open file recorder (extension can be .wav or .mp3");
+    puts  ("  --auto-rec          Automatically record conversation");
+    puts  ("  --quality=N         Specify media quality (0-10, default=6)");
+    puts  ("  --ptime=MSEC        Override codec ptime to MSEC (default=specific)");
+    puts  ("  --no-vad            Disable VAD/silence detector (default=vad enabled)");
+    puts  ("  --ec-tail=MSEC      Set echo canceller tail length (default=256)");
+    puts  ("  --ec-opt=OPT        Select echo canceller algorithm (0=default, ");
+    puts  ("                        1=speex, 2=suppressor)");
+    puts  ("  --ilbc-mode=MODE    Set iLBC codec mode (20 or 30, default is 30)");
+    puts  ("  --capture-dev=id    Audio capture device ID (default=-1)");
+    puts  ("  --playback-dev=id   Audio playback device ID (default=-1)");
+    puts  ("  --capture-lat=N     Audio capture latency, in ms (default=100)");
+    puts  ("  --playback-lat=N    Audio playback latency, in ms (default=100)");
+    puts  ("  --snd-auto-close=N  Auto close audio device when idle for N secs (default=1)");
+    puts  ("                      Specify N=-1 to disable this feature.");
+    puts  ("                      Specify N=0 for instant close when unused.");
+    puts  ("  --no-tones          Disable audible tones");
+    puts  ("  --jb-max-size       Specify jitter buffer maximum size, in frames (default=-1)");
+    puts  ("  --extra-audio       Add one more audio stream");
+
+#if PJSUA_HAS_VIDEO
+    puts  ("");
+    puts  ("Video Options:");
+    puts  ("  --video             Enable video");
+    puts  ("  --vcapture-dev=id   Video capture device ID (default=-1)");
+    puts  ("  --vrender-dev=id    Video render device ID (default=-2)");
+    puts  ("  --play-avi=FILE     Load this AVI as virtual capture device");
+    puts  ("  --auto-play-avi     Automatically play the AVI media to call");
+#endif
+
+    puts  ("");
+    puts  ("Media Transport Options:");
+    puts  ("  --use-ice           Enable ICE (default:no)");
+    puts  ("  --ice-regular       Use ICE regular nomination (default: aggressive)");
+    puts  ("  --ice-max-hosts=N   Set maximum number of ICE host candidates");
+    puts  ("  --ice-no-rtcp       Disable RTCP component in ICE (default: no)");
+    puts  ("  --rtp-port=N        Base port to try for RTP (default=4000)");
+    puts  ("  --rx-drop-pct=PCT   Drop PCT percent of RX RTP (for pkt lost sim, default: 0)");
+    puts  ("  --tx-drop-pct=PCT   Drop PCT percent of TX RTP (for pkt lost sim, default: 0)");
+    puts  ("  --use-turn          Enable TURN relay with ICE (default:no)");
+    puts  ("  --turn-srv          Domain or host name of TURN server (\"NAME:PORT\" format)");
+    puts  ("  --turn-tcp          Use TCP connection to TURN server (default no)");
+    puts  ("  --turn-user         TURN username");
+    puts  ("  --turn-passwd       TURN password");
+
+    puts  ("");
+    puts  ("Buddy List (can be more than one):");
+    puts  ("  --add-buddy url     Add the specified URL to the buddy list.");
+    puts  ("");
+    puts  ("User Agent options:");
+    puts  ("  --auto-answer=code  Automatically answer incoming calls with code (e.g. 200)");
+    puts  ("  --max-calls=N       Maximum number of concurrent calls (default:4, max:255)");
+    puts  ("  --thread-cnt=N      Number of worker threads (default:1)");
+    puts  ("  --duration=SEC      Set maximum call duration (default:no limit)");
+    puts  ("  --norefersub        Suppress event subscription when transfering calls");
+    puts  ("  --use-compact-form  Minimize SIP message size");
+    puts  ("  --no-force-lr       Allow strict-route to be used (i.e. do not force lr)");
+    puts  ("  --accept-redirect=N Specify how to handle call redirect (3xx) response.");
+    puts  ("                      0: reject, 1: follow automatically,");
+    puts  ("                      2: follow + replace To header (default), 3: ask");
+
+    puts  ("");
+    puts  ("CLI options:");
+    puts  ("  --use-cli           Use CLI as user interface");
+    puts  ("  --cli-telnet-port=N CLI telnet port");
+    puts  ("  --no-cli-console    Disable CLI console");
+    puts  ("");
+
+    puts  ("");
+    puts  ("When URL is specified, pjsua will immediately initiate call to that URL");
+    puts  ("");
+
+    fflush(stdout);
+}
+
+/*
+ * Read command arguments from config file.
+ */
+static int read_config_file(pj_pool_t *pool, const char *filename, 
+			    int *app_argc, char ***app_argv)
+{
+    int i;
+    FILE *fhnd;
+    char line[200];
+    int argc = 0;
+    char **argv;
+    enum { MAX_ARGS = 128 };
+
+    /* Allocate MAX_ARGS+1 (argv needs to be terminated with NULL argument) */
+    argv = pj_pool_calloc(pool, MAX_ARGS+1, sizeof(char*));
+    argv[argc++] = *app_argv[0];
+
+    /* Open config file. */
+    fhnd = fopen(filename, "rt");
+    if (!fhnd) {
+	PJ_LOG(1,(THIS_FILE, "Unable to open config file %s", filename));
+	fflush(stdout);
+	return -1;
+    }
+
+    /* Scan tokens in the file. */
+    while (argc < MAX_ARGS && !feof(fhnd)) {
+	char  *token;
+	char  *p;
+	const char *whitespace = " \t\r\n";
+	char  cDelimiter;
+	int   len, token_len;
+	
+	pj_bzero(line, sizeof(line));
+	if (fgets(line, sizeof(line), fhnd) == NULL) break;
+	
+	// Trim ending newlines
+	len = strlen(line);
+	if (line[len-1]=='\n')
+	    line[--len] = '\0';
+	if (line[len-1]=='\r')
+	    line[--len] = '\0';
+
+	if (len==0) continue;
+
+	for (p = line; *p != '\0' && argc < MAX_ARGS; p++) {
+	    // first, scan whitespaces
+	    while (*p != '\0' && strchr(whitespace, *p) != NULL) p++;
+
+	    if (*p == '\0')		    // are we done yet?
+		break;
+	    
+	    if (*p == '"' || *p == '\'') {    // is token a quoted string
+		cDelimiter = *p++;	    // save quote delimiter
+		token = p;
+		
+		while (*p != '\0' && *p != cDelimiter) p++;
+		
+		if (*p == '\0')		// found end of the line, but,
+		    cDelimiter = '\0';	// didn't find a matching quote
+
+	    } else {			// token's not a quoted string
+		token = p;
+		
+		while (*p != '\0' && strchr(whitespace, *p) == NULL) p++;
+		
+		cDelimiter = *p;
+	    }
+	    
+	    *p = '\0';
+	    token_len = p-token;
+	    
+	    if (token_len > 0) {
+		if (*token == '#')
+		    break;  // ignore remainder of line
+		
+		argv[argc] = pj_pool_alloc(pool, token_len + 1);
+		pj_memcpy(argv[argc], token, token_len + 1);
+		++argc;
+	    }
+	    
+	    *p = cDelimiter;
+	}
+    }
+
+    /* Copy arguments from command line */
+    for (i=1; i<*app_argc && argc < MAX_ARGS; ++i)
+	argv[argc++] = (*app_argv)[i];
+
+    if (argc == MAX_ARGS && (i!=*app_argc || !feof(fhnd))) {
+	PJ_LOG(1,(THIS_FILE, 
+		  "Too many arguments specified in cmd line/config file"));
+	fflush(stdout);
+	fclose(fhnd);
+	return -1;
+    }
+
+    fclose(fhnd);
+
+    /* Assign the new command line back to the original command line. */
+    *app_argc = argc;
+    *app_argv = argv;
+    return 0;
+}
+
+/* Parse arguments. */
+static pj_status_t parse_args(int argc, char *argv[], 
+			      pjsua_app_config *cfg,
+			      pj_str_t *uri_to_call)
+{
+    int c;
+    int option_index;
+    enum { OPT_CONFIG_FILE=127, OPT_LOG_FILE, OPT_LOG_LEVEL, OPT_APP_LOG_LEVEL, 
+	   OPT_LOG_APPEND, OPT_COLOR, OPT_NO_COLOR, OPT_LIGHT_BG, OPT_NO_STDERR,
+	   OPT_HELP, OPT_VERSION, OPT_NULL_AUDIO, OPT_SND_AUTO_CLOSE,
+	   OPT_LOCAL_PORT, OPT_IP_ADDR, OPT_PROXY, OPT_OUTBOUND_PROXY, 
+	   OPT_REGISTRAR, OPT_REG_TIMEOUT, OPT_PUBLISH, OPT_ID, OPT_CONTACT,
+	   OPT_BOUND_ADDR, OPT_CONTACT_PARAMS, OPT_CONTACT_URI_PARAMS,
+	   OPT_100REL, OPT_USE_IMS, OPT_REALM, OPT_USERNAME, OPT_PASSWORD,
+	   OPT_REG_RETRY_INTERVAL, OPT_REG_USE_PROXY,
+	   OPT_MWI, OPT_NAMESERVER, OPT_STUN_SRV, OPT_OUTB_RID,
+	   OPT_ADD_BUDDY, OPT_OFFER_X_MS_MSG, OPT_NO_PRESENCE,
+	   OPT_AUTO_ANSWER, OPT_AUTO_PLAY, OPT_AUTO_PLAY_HANGUP, OPT_AUTO_LOOP,
+	   OPT_AUTO_CONF, OPT_CLOCK_RATE, OPT_SND_CLOCK_RATE, OPT_STEREO,
+	   OPT_USE_ICE, OPT_ICE_REGULAR, OPT_USE_SRTP, OPT_SRTP_SECURE,
+	   OPT_USE_TURN, OPT_ICE_MAX_HOSTS, OPT_ICE_NO_RTCP, OPT_TURN_SRV, 
+	   OPT_TURN_TCP, OPT_TURN_USER, OPT_TURN_PASSWD,
+	   OPT_PLAY_FILE, OPT_PLAY_TONE, OPT_RTP_PORT, OPT_ADD_CODEC, 
+	   OPT_ILBC_MODE, OPT_REC_FILE, OPT_AUTO_REC,
+	   OPT_COMPLEXITY, OPT_QUALITY, OPT_PTIME, OPT_NO_VAD,
+	   OPT_RX_DROP_PCT, OPT_TX_DROP_PCT, OPT_EC_TAIL, OPT_EC_OPT,
+	   OPT_NEXT_ACCOUNT, OPT_NEXT_CRED, OPT_MAX_CALLS, 
+	   OPT_DURATION, OPT_NO_TCP, OPT_NO_UDP, OPT_THREAD_CNT,
+	   OPT_NOREFERSUB, OPT_ACCEPT_REDIRECT,
+	   OPT_USE_TLS, OPT_TLS_CA_FILE, OPT_TLS_CERT_FILE, OPT_TLS_PRIV_FILE,
+	   OPT_TLS_PASSWORD, OPT_TLS_VERIFY_SERVER, OPT_TLS_VERIFY_CLIENT,
+	   OPT_TLS_NEG_TIMEOUT, OPT_TLS_CIPHER,
+	   OPT_CAPTURE_DEV, OPT_PLAYBACK_DEV,
+	   OPT_CAPTURE_LAT, OPT_PLAYBACK_LAT, OPT_NO_TONES, OPT_JB_MAX_SIZE,
+	   OPT_STDOUT_REFRESH, OPT_STDOUT_REFRESH_TEXT, OPT_IPV6, OPT_QOS,
+#ifdef _IONBF
+	   OPT_STDOUT_NO_BUF,
+#endif
+	   OPT_AUTO_UPDATE_NAT,OPT_USE_COMPACT_FORM,OPT_DIS_CODEC,
+	   OPT_DISABLE_STUN, OPT_NO_FORCE_LR,
+	   OPT_TIMER, OPT_TIMER_SE, OPT_TIMER_MIN_SE,
+	   OPT_VIDEO, OPT_EXTRA_AUDIO,
+	   OPT_VCAPTURE_DEV, OPT_VRENDER_DEV, OPT_PLAY_AVI, OPT_AUTO_PLAY_AVI,
+	   OPT_USE_CLI, OPT_CLI_TELNET_PORT, OPT_DISABLE_CLI_CONSOLE
+    };
+    struct pj_getopt_option long_options[] = {
+	{ "config-file",1, 0, OPT_CONFIG_FILE},
+	{ "log-file",	1, 0, OPT_LOG_FILE},
+	{ "log-level",	1, 0, OPT_LOG_LEVEL},
+	{ "app-log-level",1,0,OPT_APP_LOG_LEVEL},
+	{ "log-append", 0, 0, OPT_LOG_APPEND},
+	{ "color",	0, 0, OPT_COLOR},
+	{ "no-color",	0, 0, OPT_NO_COLOR},
+	{ "light-bg",		0, 0, OPT_LIGHT_BG},
+	{ "no-stderr",  0, 0, OPT_NO_STDERR},
+	{ "help",	0, 0, OPT_HELP},
+	{ "version",	0, 0, OPT_VERSION},
+	{ "clock-rate",	1, 0, OPT_CLOCK_RATE},
+	{ "snd-clock-rate",	1, 0, OPT_SND_CLOCK_RATE},
+	{ "stereo",	0, 0, OPT_STEREO},
+	{ "null-audio", 0, 0, OPT_NULL_AUDIO},
+	{ "local-port", 1, 0, OPT_LOCAL_PORT},
+	{ "ip-addr",	1, 0, OPT_IP_ADDR},
+	{ "bound-addr", 1, 0, OPT_BOUND_ADDR},
+	{ "no-tcp",     0, 0, OPT_NO_TCP},
+	{ "no-udp",     0, 0, OPT_NO_UDP},
+	{ "norefersub", 0, 0, OPT_NOREFERSUB},
+	{ "proxy",	1, 0, OPT_PROXY},
+	{ "outbound",	1, 0, OPT_OUTBOUND_PROXY},
+	{ "registrar",	1, 0, OPT_REGISTRAR},
+	{ "reg-timeout",1, 0, OPT_REG_TIMEOUT},
+	{ "publish",    0, 0, OPT_PUBLISH},
+	{ "mwi",	0, 0, OPT_MWI},
+	{ "use-100rel", 0, 0, OPT_100REL},
+	{ "use-ims",    0, 0, OPT_USE_IMS},
+	{ "id",		1, 0, OPT_ID},
+	{ "contact",	1, 0, OPT_CONTACT},
+	{ "contact-params",1,0, OPT_CONTACT_PARAMS},
+	{ "contact-uri-params",1,0, OPT_CONTACT_URI_PARAMS},
+	{ "auto-update-nat",	1, 0, OPT_AUTO_UPDATE_NAT},
+	{ "disable-stun",0,0, OPT_DISABLE_STUN},
+        { "use-compact-form",	0, 0, OPT_USE_COMPACT_FORM},
+	{ "accept-redirect", 1, 0, OPT_ACCEPT_REDIRECT},
+	{ "no-force-lr",0, 0, OPT_NO_FORCE_LR},
+	{ "realm",	1, 0, OPT_REALM},
+	{ "username",	1, 0, OPT_USERNAME},
+	{ "password",	1, 0, OPT_PASSWORD},
+	{ "rereg-delay",1, 0, OPT_REG_RETRY_INTERVAL},
+	{ "reg-use-proxy", 1, 0, OPT_REG_USE_PROXY},
+	{ "nameserver", 1, 0, OPT_NAMESERVER},
+	{ "stun-srv",   1, 0, OPT_STUN_SRV},
+	{ "add-buddy",  1, 0, OPT_ADD_BUDDY},
+	{ "offer-x-ms-msg",0,0,OPT_OFFER_X_MS_MSG},
+	{ "no-presence", 0, 0, OPT_NO_PRESENCE},
+	{ "auto-answer",1, 0, OPT_AUTO_ANSWER},
+	{ "auto-play",  0, 0, OPT_AUTO_PLAY},
+	{ "auto-play-hangup",0, 0, OPT_AUTO_PLAY_HANGUP},
+	{ "auto-rec",   0, 0, OPT_AUTO_REC},
+	{ "auto-loop",  0, 0, OPT_AUTO_LOOP},
+	{ "auto-conf",  0, 0, OPT_AUTO_CONF},
+	{ "play-file",  1, 0, OPT_PLAY_FILE},
+	{ "play-tone",  1, 0, OPT_PLAY_TONE},
+	{ "rec-file",   1, 0, OPT_REC_FILE},
+	{ "rtp-port",	1, 0, OPT_RTP_PORT},
+
+	{ "use-ice",    0, 0, OPT_USE_ICE},
+	{ "ice-regular",0, 0, OPT_ICE_REGULAR},
+	{ "use-turn",	0, 0, OPT_USE_TURN},
+	{ "ice-max-hosts",1, 0, OPT_ICE_MAX_HOSTS},
+	{ "ice-no-rtcp",0, 0, OPT_ICE_NO_RTCP},
+	{ "turn-srv",	1, 0, OPT_TURN_SRV},
+	{ "turn-tcp",	0, 0, OPT_TURN_TCP},
+	{ "turn-user",	1, 0, OPT_TURN_USER},
+	{ "turn-passwd",1, 0, OPT_TURN_PASSWD},
+
+#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
+	{ "use-srtp",   1, 0, OPT_USE_SRTP},
+	{ "srtp-secure",1, 0, OPT_SRTP_SECURE},
+#endif
+	{ "add-codec",  1, 0, OPT_ADD_CODEC},
+	{ "dis-codec",  1, 0, OPT_DIS_CODEC},
+	{ "complexity",	1, 0, OPT_COMPLEXITY},
+	{ "quality",	1, 0, OPT_QUALITY},
+	{ "ptime",      1, 0, OPT_PTIME},
+	{ "no-vad",     0, 0, OPT_NO_VAD},
+	{ "ec-tail",    1, 0, OPT_EC_TAIL},
+	{ "ec-opt",	1, 0, OPT_EC_OPT},
+	{ "ilbc-mode",	1, 0, OPT_ILBC_MODE},
+	{ "rx-drop-pct",1, 0, OPT_RX_DROP_PCT},
+	{ "tx-drop-pct",1, 0, OPT_TX_DROP_PCT},
+	{ "next-account",0,0, OPT_NEXT_ACCOUNT},
+	{ "next-cred",	0, 0, OPT_NEXT_CRED},
+	{ "max-calls",	1, 0, OPT_MAX_CALLS},
+	{ "duration",	1, 0, OPT_DURATION},
+	{ "thread-cnt",	1, 0, OPT_THREAD_CNT},
+#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
+	{ "use-tls",	0, 0, OPT_USE_TLS}, 
+	{ "tls-ca-file",1, 0, OPT_TLS_CA_FILE},
+	{ "tls-cert-file",1,0, OPT_TLS_CERT_FILE}, 
+	{ "tls-privkey-file",1,0, OPT_TLS_PRIV_FILE},
+	{ "tls-password",1,0, OPT_TLS_PASSWORD},
+	{ "tls-verify-server", 0, 0, OPT_TLS_VERIFY_SERVER},
+	{ "tls-verify-client", 0, 0, OPT_TLS_VERIFY_CLIENT},
+	{ "tls-neg-timeout", 1, 0, OPT_TLS_NEG_TIMEOUT},
+	{ "tls-cipher", 1, 0, OPT_TLS_CIPHER},
+#endif
+	{ "capture-dev",    1, 0, OPT_CAPTURE_DEV},
+	{ "playback-dev",   1, 0, OPT_PLAYBACK_DEV},
+	{ "capture-lat",    1, 0, OPT_CAPTURE_LAT},
+	{ "playback-lat",   1, 0, OPT_PLAYBACK_LAT},
+	{ "stdout-refresh", 1, 0, OPT_STDOUT_REFRESH},
+	{ "stdout-refresh-text", 1, 0, OPT_STDOUT_REFRESH_TEXT},
+#ifdef _IONBF
+	{ "stdout-no-buf",  0, 0, OPT_STDOUT_NO_BUF },
+#endif
+	{ "snd-auto-close", 1, 0, OPT_SND_AUTO_CLOSE},
+	{ "no-tones",    0, 0, OPT_NO_TONES},
+	{ "jb-max-size", 1, 0, OPT_JB_MAX_SIZE},
+#if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6
+	{ "ipv6",	 0, 0, OPT_IPV6},
+#endif
+	{ "set-qos",	 0, 0, OPT_QOS},
+	{ "use-timer",  1, 0, OPT_TIMER},
+	{ "timer-se",   1, 0, OPT_TIMER_SE},
+	{ "timer-min-se", 1, 0, OPT_TIMER_MIN_SE},
+	{ "outb-rid",	1, 0, OPT_OUTB_RID},
+	{ "video",	0, 0, OPT_VIDEO},
+	{ "extra-audio",0, 0, OPT_EXTRA_AUDIO},
+	{ "vcapture-dev", 1, 0, OPT_VCAPTURE_DEV},
+	{ "vrender-dev",  1, 0, OPT_VRENDER_DEV},
+	{ "play-avi",	1, 0, OPT_PLAY_AVI},
+	{ "auto-play-avi", 0, 0, OPT_AUTO_PLAY_AVI},
+	{ "use-cli",	0, 0, OPT_USE_CLI},
+	{ "cli-telnet-port", 1, 0, OPT_CLI_TELNET_PORT},
+	{ "no-cli-console", 0, 0, OPT_DISABLE_CLI_CONSOLE},
+	{ NULL, 0, 0, 0}
+    };
+    pj_status_t status;
+    pjsua_acc_config *cur_acc;
+    char *config_file = NULL;
+    unsigned i;
+
+    /* Run pj_getopt once to see if user specifies config file to read. */ 
+    pj_optind = 0;
+    while ((c=pj_getopt_long(argc, argv, "", long_options, 
+			     &option_index)) != -1) 
+    {
+	switch (c) {
+	case OPT_CONFIG_FILE:
+	    config_file = pj_optarg;
+	    break;
+	}
+	if (config_file)
+	    break;
+    }
+
+    if (config_file) {
+	status = read_config_file(cfg->pool, config_file, &argc, &argv);
+	if (status != 0)
+	    return status;
+    }
+
+    cfg->acc_cnt = 0;
+    cur_acc = &cfg->acc_cfg[0];
+
+
+    /* Reinitialize and re-run pj_getopt again, possibly with new arguments
+     * read from config file.
+     */
+    pj_optind = 0;
+    while((c=pj_getopt_long(argc,argv, "", long_options,&option_index))!=-1) {
+	pj_str_t tmp;
+	long lval;
+
+	switch (c) {
+
+	case OPT_CONFIG_FILE:
+	    /* Ignore as this has been processed before */
+	    break;
+	
+	case OPT_LOG_FILE:
+	    cfg->log_cfg.log_filename = pj_str(pj_optarg);
+	    break;
+
+	case OPT_LOG_LEVEL:
+	    c = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (c < 0 || c > 6) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: expecting integer value 0-6 "
+			  "for --log-level"));
+		return PJ_EINVAL;
+	    }
+	    cfg->log_cfg.level = c;
+	    pj_log_set_level( c );
+	    break;
+
+	case OPT_APP_LOG_LEVEL:
+	    cfg->log_cfg.console_level = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (cfg->log_cfg.console_level < 0 || cfg->log_cfg.console_level > 6) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: expecting integer value 0-6 "
+			  "for --app-log-level"));
+		return PJ_EINVAL;
+	    }
+	    break;
+
+	case OPT_LOG_APPEND:
+	    cfg->log_cfg.log_file_flags |= PJ_O_APPEND;
+	    break;
+
+	case OPT_COLOR:
+	    cfg->log_cfg.decor |= PJ_LOG_HAS_COLOR;
+	    break;
+
+	case OPT_NO_COLOR:
+	    cfg->log_cfg.decor &= ~PJ_LOG_HAS_COLOR;
+	    break;
+
+	case OPT_LIGHT_BG:
+	    pj_log_set_color(1, PJ_TERM_COLOR_R);
+	    pj_log_set_color(2, PJ_TERM_COLOR_R | PJ_TERM_COLOR_G);
+	    pj_log_set_color(3, PJ_TERM_COLOR_B | PJ_TERM_COLOR_G);
+	    pj_log_set_color(4, 0);
+	    pj_log_set_color(5, 0);
+	    pj_log_set_color(77, 0);
+	    break;
+
+	case OPT_NO_STDERR:
+	    freopen("/dev/null", "w", stderr);
+	    break;
+
+	case OPT_HELP:
+	    usage();
+	    return PJ_EINVAL;
+
+	case OPT_VERSION:   /* version */
+	    pj_dump_config();
+	    return PJ_EINVAL;
+
+	case OPT_NULL_AUDIO:
+	    cfg->null_audio = PJ_TRUE;
+	    break;
+
+	case OPT_CLOCK_RATE:
+	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (lval < 8000 || lval > 192000) {
+		PJ_LOG(1,(THIS_FILE, "Error: expecting value between "
+				     "8000-192000 for conference clock rate"));
+		return PJ_EINVAL;
+	    }
+	    cfg->media_cfg.clock_rate = lval; 
+	    break;
+
+	case OPT_SND_CLOCK_RATE:
+	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (lval < 8000 || lval > 192000) {
+		PJ_LOG(1,(THIS_FILE, "Error: expecting value between "
+				     "8000-192000 for sound device clock rate"));
+		return PJ_EINVAL;
+	    }
+	    cfg->media_cfg.snd_clock_rate = lval; 
+	    break;
+
+	case OPT_STEREO:
+	    cfg->media_cfg.channel_count = 2;
+	    break;
+
+	case OPT_LOCAL_PORT:   /* local-port */
+	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (lval < 0 || lval > 65535) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: expecting integer value for "
+			  "--local-port"));
+		return PJ_EINVAL;
+	    }
+	    cfg->udp_cfg.port = (pj_uint16_t)lval;
+	    break;
+
+	case OPT_IP_ADDR: /* ip-addr */
+	    cfg->udp_cfg.public_addr = pj_str(pj_optarg);
+	    cfg->rtp_cfg.public_addr = pj_str(pj_optarg);
+	    break;
+
+	case OPT_BOUND_ADDR: /* bound-addr */
+	    cfg->udp_cfg.bound_addr = pj_str(pj_optarg);
+	    cfg->rtp_cfg.bound_addr = pj_str(pj_optarg);
+	    break;
+
+	case OPT_NO_UDP: /* no-udp */
+	    if (cfg->no_tcp && !cfg->use_tls) {
+	      PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP"));
+	      return PJ_EINVAL;
+	    }
+
+	    cfg->no_udp = PJ_TRUE;
+	    break;
+
+	case OPT_NOREFERSUB: /* norefersub */
+	    cfg->no_refersub = PJ_TRUE;
+	    break;
+
+	case OPT_NO_TCP: /* no-tcp */
+	    if (cfg->no_udp && !cfg->use_tls) {
+	      PJ_LOG(1,(THIS_FILE,"Error: cannot disable both TCP and UDP"));
+	      return PJ_EINVAL;
+	    }
+
+	    cfg->no_tcp = PJ_TRUE;
+	    break;
+
+	case OPT_PROXY:   /* proxy */
+	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid SIP URL '%s' "
+			  "in proxy argument", pj_optarg));
+		return PJ_EINVAL;
+	    }
+	    cur_acc->proxy[cur_acc->proxy_cnt++] = pj_str(pj_optarg);
+	    break;
+
+	case OPT_OUTBOUND_PROXY:   /* outbound proxy */
+	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid SIP URL '%s' "
+			  "in outbound proxy argument", pj_optarg));
+		return PJ_EINVAL;
+	    }
+	    cfg->cfg.outbound_proxy[cfg->cfg.outbound_proxy_cnt++] = pj_str(pj_optarg);
+	    break;
+
+	case OPT_REGISTRAR:   /* registrar */
+	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid SIP URL '%s' in "
+			  "registrar argument", pj_optarg));
+		return PJ_EINVAL;
+	    }
+	    cur_acc->reg_uri = pj_str(pj_optarg);
+	    break;
+
+	case OPT_REG_TIMEOUT:   /* reg-timeout */
+	    cur_acc->reg_timeout = pj_strtoul(pj_cstr(&tmp,pj_optarg));
+	    if (cur_acc->reg_timeout < 1 || cur_acc->reg_timeout > 3600) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid value for --reg-timeout "
+			  "(expecting 1-3600)"));
+		return PJ_EINVAL;
+	    }
+	    break;
+
+	case OPT_PUBLISH:   /* publish */
+	    cur_acc->publish_enabled = PJ_TRUE;
+	    break;
+
+	case OPT_MWI:	/* mwi */
+	    cur_acc->mwi_enabled = PJ_TRUE;
+	    break;
+
+	case OPT_100REL: /** 100rel */
+	    cur_acc->require_100rel = PJSUA_100REL_MANDATORY;
+	    cfg->cfg.require_100rel = PJSUA_100REL_MANDATORY;
+	    break;
+
+	case OPT_TIMER: /** session timer */
+	    lval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (lval < 0 || lval > 3) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: expecting integer value 0-3 for --use-timer"));
+		return PJ_EINVAL;
+	    }
+	    cur_acc->use_timer = lval;
+	    cfg->cfg.use_timer = lval;
+	    break;
+
+	case OPT_TIMER_SE: /** session timer session expiration */
+	    cur_acc->timer_setting.sess_expires = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (cur_acc->timer_setting.sess_expires < 90) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid value for --timer-se "
+			  "(expecting higher than 90)"));
+		return PJ_EINVAL;
+	    }
+	    cfg->cfg.timer_setting.sess_expires = cur_acc->timer_setting.sess_expires;
+	    break;
+
+	case OPT_TIMER_MIN_SE: /** session timer minimum session expiration */
+	    cur_acc->timer_setting.min_se = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (cur_acc->timer_setting.min_se < 90) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid value for --timer-min-se "
+			  "(expecting higher than 90)"));
+		return PJ_EINVAL;
+	    }
+	    cfg->cfg.timer_setting.min_se = cur_acc->timer_setting.min_se;
+	    break;
+
+	case OPT_OUTB_RID: /* Outbound reg-id */
+	    cur_acc->rfc5626_reg_id = pj_str(pj_optarg);
+	    break;
+
+	case OPT_USE_IMS: /* Activate IMS settings */
+	    cur_acc->auth_pref.initial_auth = PJ_TRUE;
+	    break;
+
+	case OPT_ID:   /* id */
+	    if (pjsua_verify_url(pj_optarg) != 0) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid SIP URL '%s' "
+			  "in local id argument", pj_optarg));
+		return PJ_EINVAL;
+	    }
+	    cur_acc->id = pj_str(pj_optarg);
+	    break;
+
+	case OPT_CONTACT:   /* contact */
+	    if (pjsua_verify_sip_url(pj_optarg) != 0) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid SIP URL '%s' "
+			  "in contact argument", pj_optarg));
+		return PJ_EINVAL;
+	    }
+	    cur_acc->force_contact = pj_str(pj_optarg);
+	    break;
+
+	case OPT_CONTACT_PARAMS:
+	    cur_acc->contact_params = pj_str(pj_optarg);
+	    break;
+
+	case OPT_CONTACT_URI_PARAMS:
+	    cur_acc->contact_uri_params = pj_str(pj_optarg);
+	    break;
+
+	case OPT_AUTO_UPDATE_NAT:   /* OPT_AUTO_UPDATE_NAT */
+            cur_acc->allow_contact_rewrite  = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    break;
+
+	case OPT_DISABLE_STUN:
+	    cur_acc->sip_stun_use = PJSUA_STUN_USE_DISABLED;
+	    cur_acc->media_stun_use = PJSUA_STUN_USE_DISABLED;
+	    break;
+
+	case OPT_USE_COMPACT_FORM:
+	    /* enable compact form - from Ticket #342 */
+            {
+		extern pj_bool_t pjsip_use_compact_form;
+		extern pj_bool_t pjsip_include_allow_hdr_in_dlg;
+		extern pj_bool_t pjmedia_add_rtpmap_for_static_pt;
+
+		pjsip_use_compact_form = PJ_TRUE;
+		/* do not transmit Allow header */
+		pjsip_include_allow_hdr_in_dlg = PJ_FALSE;
+		/* Do not include rtpmap for static payload types (<96) */
+		pjmedia_add_rtpmap_for_static_pt = PJ_FALSE;
+            }
+	    break;
+
+	case OPT_ACCEPT_REDIRECT:
+	    cfg->redir_op = my_atoi(pj_optarg);
+	    if (cfg->redir_op<0 || cfg->redir_op>PJSIP_REDIRECT_STOP) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: accept-redirect value '%s' ", pj_optarg));
+		return PJ_EINVAL;
+	    }
+	    break;
+
+	case OPT_NO_FORCE_LR:
+	    cfg->cfg.force_lr = PJ_FALSE;
+	    break;
+
+	case OPT_NEXT_ACCOUNT: /* Add more account. */
+	    cfg->acc_cnt++;
+	    cur_acc = &cfg->acc_cfg[cfg->acc_cnt];
+	    break;
+
+	case OPT_USERNAME:   /* Default authentication user */
+	    cur_acc->cred_info[cur_acc->cred_count].username = pj_str(pj_optarg);
+	    cur_acc->cred_info[cur_acc->cred_count].scheme = pj_str("Digest");
+	    break;
+
+	case OPT_REALM:	    /* Default authentication realm. */
+	    cur_acc->cred_info[cur_acc->cred_count].realm = pj_str(pj_optarg);
+	    break;
+
+	case OPT_PASSWORD:   /* authentication password */
+	    cur_acc->cred_info[cur_acc->cred_count].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
+	    cur_acc->cred_info[cur_acc->cred_count].data = pj_str(pj_optarg);
+#if PJSIP_HAS_DIGEST_AKA_AUTH
+	    cur_acc->cred_info[cur_acc->cred_count].data_type |= PJSIP_CRED_DATA_EXT_AKA;
+	    cur_acc->cred_info[cur_acc->cred_count].ext.aka.k = pj_str(pj_optarg);
+	    cur_acc->cred_info[cur_acc->cred_count].ext.aka.cb = &pjsip_auth_create_aka_response;
+#endif
+	    break;
+
+	case OPT_REG_RETRY_INTERVAL:
+	    cur_acc->reg_retry_interval = pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    break;
+
+	case OPT_REG_USE_PROXY:
+	    cur_acc->reg_use_proxy = (unsigned)pj_strtoul(pj_cstr(&tmp, pj_optarg));
+	    if (cur_acc->reg_use_proxy > 3) {
+		PJ_LOG(1,(THIS_FILE, "Error: invalid --reg-use-proxy value '%s'",
+			  pj_optarg));
+		return PJ_EINVAL;
+	    }
+	    break;
+
+	case OPT_NEXT_CRED: /* next credential */
+	    cur_acc->cred_count++;
+	    break;
+
+	case OPT_NAMESERVER: /* nameserver */
+	    cfg->cfg.nameserver[cfg->cfg.nameserver_count++] = pj_str(pj_optarg);
+	    if (cfg->cfg.nameserver_count > PJ_ARRAY_SIZE(cfg->cfg.nameserver)) {
+		PJ_LOG(1,(THIS_FILE, "Error: too many nameservers"));
+		return PJ_ETOOMANY;
+	    }
+	    break;
+
+	case OPT_STUN_SRV:   /* STUN server */
+	    cfg->cfg.stun_host = pj_str(pj_optarg);
+	    if (cfg->cfg.stun_srv_cnt==PJ_ARRAY_SIZE(cfg->cfg.stun_srv)) {
+		PJ_LOG(1,(THIS_FILE, "Error: too many STUN servers"));
+		return PJ_ETOOMANY;
+	    }
+	    cfg->cfg.stun_srv[cfg->cfg.stun_srv_cnt++] = pj_str(pj_optarg);
+	    break;
+
+	case OPT_ADD_BUDDY: /* Add to buddy list. */
+	    if (pjsua_verify_url(pj_optarg) != 0) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: invalid URL '%s' in "
+			  "--add-buddy option", pj_optarg));
+		return -1;
+	    }
+	    if (cfg->buddy_cnt == PJ_ARRAY_SIZE(cfg->buddy_cfg)) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: too many buddies in buddy list."));
+		return -1;
+	    }
+	    cfg->buddy_cfg[cfg->buddy_cnt].uri = pj_str(pj_optarg);
+	    cfg->buddy_cnt++;
+	    break;
+
+	case OPT_AUTO_PLAY:
+	    cfg->auto_play = 1;
+	    break;
+
+	case OPT_AUTO_PLAY_HANGUP:
+	    cfg->auto_play_hangup = 1;
+	    break;
+
+	case OPT_AUTO_REC:
+	    cfg->auto_rec = 1;
+	    break;
+
+	case OPT_AUTO_LOOP:
+	    cfg->auto_loop = 1;
+	    break;
+
+	case OPT_AUTO_CONF:
+	    cfg->auto_conf = 1;
+	    break;
+
+	case OPT_PLAY_FILE:
+	    cfg->wav_files[cfg->wav_count++] = pj_str(pj_optarg);
+	    break;
+
+	case OPT_PLAY_TONE:
+	    {
+		int f1, f2, on, off;
+		int n;
+
+		n = sscanf(pj_optarg, "%d,%d,%d,%d", &f1, &f2, &on, &off);
+		if (n != 4) {
+		    puts("Expecting f1,f2,on,off in --play-tone");
+		    return -1;
+		}
+
+		cfg->tones[cfg->tone_count].freq1 = (short)f1;
+		cfg->tones[cfg->tone_count].freq2 = (short)f2;
+		cfg->tones[cfg->tone_count].on_msec = (short)on;
+		cfg->tones[cfg->tone_count].off_msec = (short)off;
+		++cfg->tone_count;
+	    }
+	    break;
+
+	case OPT_REC_FILE:
+	    cfg->rec_file = pj_str(pj_optarg);
+	    break;
+
+	case OPT_USE_ICE:
+	    cfg->media_cfg.enable_ice =
+		    cur_acc->ice_cfg.enable_ice = PJ_TRUE;
+	    break;
+
+	case OPT_ICE_REGULAR:
+	    cfg->media_cfg.ice_opt.aggressive =
+		    cur_acc->ice_cfg.ice_opt.aggressive = PJ_FALSE;
+	    break;
+
+	case OPT_USE_TURN:
+	    cfg->media_cfg.enable_turn =
+		    cur_acc->turn_cfg.enable_turn = PJ_TRUE;
+	    break;
+
+	case OPT_ICE_MAX_HOSTS:
+	    cfg->media_cfg.ice_max_host_cands =
+		    cur_acc->ice_cfg.ice_max_host_cands = my_atoi(pj_optarg);
+	    break;
+
+	case OPT_ICE_NO_RTCP:
+	    cfg->media_cfg.ice_no_rtcp =
+		    cur_acc->ice_cfg.ice_no_rtcp = PJ_TRUE;
+	    break;
+
+	case OPT_TURN_SRV:
+	    cfg->media_cfg.turn_server =
+		    cur_acc->turn_cfg.turn_server = pj_str(pj_optarg);
+	    break;
+
+	case OPT_TURN_TCP:
+	    cfg->media_cfg.turn_conn_type =
+		    cur_acc->turn_cfg.turn_conn_type = PJ_TURN_TP_TCP;
+	    break;
+
+	case OPT_TURN_USER:
+	    cfg->media_cfg.turn_auth_cred.type =
+		    cur_acc->turn_cfg.turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC;
+	    cfg->media_cfg.turn_auth_cred.data.static_cred.realm =
+		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.realm = pj_str("*");
+	    cfg->media_cfg.turn_auth_cred.data.static_cred.username =
+		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.username = pj_str(pj_optarg);
+	    break;
+
+	case OPT_TURN_PASSWD:
+	    cfg->media_cfg.turn_auth_cred.data.static_cred.data_type =
+		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
+	    cfg->media_cfg.turn_auth_cred.data.static_cred.data =
+		    cur_acc->turn_cfg.turn_auth_cred.data.static_cred.data = pj_str(pj_optarg);
+	    break;
+
+#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
+	case OPT_USE_SRTP:
+	    app_config.cfg.use_srtp = my_atoi(pj_optarg);
+	    if (!pj_isdigit(*pj_optarg) || app_config.cfg.use_srtp > 3) {
+		PJ_LOG(1,(THIS_FILE, "Invalid value for --use-srtp option"));
+		return -1;
+	    }
+	    if ((int)app_config.cfg.use_srtp == 3) {
+		/* SRTP optional mode with duplicated media offer */
+		app_config.cfg.use_srtp = PJMEDIA_SRTP_OPTIONAL;
+		app_config.cfg.srtp_optional_dup_offer = PJ_TRUE;
+		cur_acc->srtp_optional_dup_offer = PJ_TRUE;
+	    }
+	    cur_acc->use_srtp = app_config.cfg.use_srtp;
+	    break;
+	case OPT_SRTP_SECURE:
+	    app_config.cfg.srtp_secure_signaling = my_atoi(pj_optarg);
+	    if (!pj_isdigit(*pj_optarg) || 
+		app_config.cfg.srtp_secure_signaling > 2) 
+	    {
+		PJ_LOG(1,(THIS_FILE, "Invalid value for --srtp-secure option"));
+		return -1;
+	    }
+	    cur_acc->srtp_secure_signaling = app_config.cfg.srtp_secure_signaling;
+	    break;
+#endif
+
+	case OPT_RTP_PORT:
+	    cfg->rtp_cfg.port = my_atoi(pj_optarg);
+	    if (cfg->rtp_cfg.port == 0) {
+		enum { START_PORT=4000 };
+		unsigned range;
+
+		range = (65535-START_PORT-PJSUA_MAX_CALLS*2);
+		cfg->rtp_cfg.port = START_PORT + 
+				    ((pj_rand() % range) & 0xFFFE);
+	    }
+
+	    if (cfg->rtp_cfg.port < 1 || cfg->rtp_cfg.port > 65535) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: rtp-port argument value "
+			  "(expecting 1-65535"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_DIS_CODEC:
+            cfg->codec_dis[cfg->codec_dis_cnt++] = pj_str(pj_optarg);
+	    break;
+
+	case OPT_ADD_CODEC:
+	    cfg->codec_arg[cfg->codec_cnt++] = pj_str(pj_optarg);
+	    break;
+
+	/* These options were no longer valid after new pjsua */
+	/*
+	case OPT_COMPLEXITY:
+	    cfg->complexity = my_atoi(pj_optarg);
+	    if (cfg->complexity < 0 || cfg->complexity > 10) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid --complexity (expecting 0-10"));
+		return -1;
+	    }
+	    break;
+	*/
+
+	case OPT_DURATION:
+	    cfg->duration = my_atoi(pj_optarg);
+	    break;
+
+	case OPT_THREAD_CNT:
+	    cfg->cfg.thread_cnt = my_atoi(pj_optarg);
+	    if (cfg->cfg.thread_cnt > 128) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid --thread-cnt option"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_PTIME:
+	    cfg->media_cfg.ptime = my_atoi(pj_optarg);
+	    if (cfg->media_cfg.ptime < 10 || cfg->media_cfg.ptime > 1000) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid --ptime option"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_NO_VAD:
+	    cfg->media_cfg.no_vad = PJ_TRUE;
+	    break;
+
+	case OPT_EC_TAIL:
+	    cfg->media_cfg.ec_tail_len = my_atoi(pj_optarg);
+	    if (cfg->media_cfg.ec_tail_len > 1000) {
+		PJ_LOG(1,(THIS_FILE, "I think the ec-tail length setting "
+			  "is too big"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_EC_OPT:
+	    cfg->media_cfg.ec_options = my_atoi(pj_optarg);
+	    break;
+
+	case OPT_QUALITY:
+	    cfg->media_cfg.quality = my_atoi(pj_optarg);
+	    if (cfg->media_cfg.quality < 0 || cfg->media_cfg.quality > 10) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid --quality (expecting 0-10"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_ILBC_MODE:
+	    cfg->media_cfg.ilbc_mode = my_atoi(pj_optarg);
+	    if (cfg->media_cfg.ilbc_mode!=20 && cfg->media_cfg.ilbc_mode!=30) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid --ilbc-mode (expecting 20 or 30"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_RX_DROP_PCT:
+	    cfg->media_cfg.rx_drop_pct = my_atoi(pj_optarg);
+	    if (cfg->media_cfg.rx_drop_pct > 100) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid --rx-drop-pct (expecting <= 100"));
+		return -1;
+	    }
+	    break;
+	    
+	case OPT_TX_DROP_PCT:
+	    cfg->media_cfg.tx_drop_pct = my_atoi(pj_optarg);
+	    if (cfg->media_cfg.tx_drop_pct > 100) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid --tx-drop-pct (expecting <= 100"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_AUTO_ANSWER:
+	    cfg->auto_answer = my_atoi(pj_optarg);
+	    if (cfg->auto_answer < 100 || cfg->auto_answer > 699) {
+		PJ_LOG(1,(THIS_FILE,
+			  "Error: invalid code in --auto-answer "
+			  "(expecting 100-699"));
+		return -1;
+	    }
+	    break;
+
+	case OPT_MAX_CALLS:
+	    cfg->cfg.max_calls = my_atoi(pj_optarg);
+	    if (cfg->cfg.max_calls < 1 || cfg->cfg.max_calls > PJSUA_MAX_CALLS) {
+		PJ_LOG(1,(THIS_FILE,"Error: maximum call setting exceeds "
+				    "compile time limit (PJSUA_MAX_CALLS=%d)",
+			  PJSUA_MAX_CALLS));
+		return -1;
+	    }
+	    break;
+
+#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
+	case OPT_USE_TLS:
+	    cfg->use_tls = PJ_TRUE;
+	    break;
+	    
+	case OPT_TLS_CA_FILE:
+	    cfg->udp_cfg.tls_setting.ca_list_file = pj_str(pj_optarg);
+	    break;
+	    
+	case OPT_TLS_CERT_FILE:
+	    cfg->udp_cfg.tls_setting.cert_file = pj_str(pj_optarg);
+	    break;
+	    
+	case OPT_TLS_PRIV_FILE:
+	    cfg->udp_cfg.tls_setting.privkey_file = pj_str(pj_optarg);
+	    break;
+
+	case OPT_TLS_PASSWORD:
+	    cfg->udp_cfg.tls_setting.password = pj_str(pj_optarg);
+	    break;
+
+	case OPT_TLS_VERIFY_SERVER:
+	    cfg->udp_cfg.tls_setting.verify_server = PJ_TRUE;
+	    break;
+
+	case OPT_TLS_VERIFY_CLIENT:
+	    cfg->udp_cfg.tls_setting.verify_client = PJ_TRUE;
+	    cfg->udp_cfg.tls_setting.require_client_cert = PJ_TRUE;
+	    break;
+
+	case OPT_TLS_NEG_TIMEOUT:
+	    cfg->udp_cfg.tls_setting.timeout.sec = atoi(pj_optarg);
+	    break;
+
+	case OPT_TLS_CIPHER:
+	    {
+		pj_ssl_cipher cipher;
+
+		if (pj_ansi_strnicmp(pj_optarg, "0x", 2) == 0) {
+		    pj_str_t cipher_st = pj_str(pj_optarg + 2);
+		    cipher = pj_strtoul2(&cipher_st, NULL, 16);
+		} else {
+		    cipher = atoi(pj_optarg);
+		}
+
+		if (pj_ssl_cipher_is_supported(cipher)) {
+		    static pj_ssl_cipher tls_ciphers[128];
+
+		    tls_ciphers[cfg->udp_cfg.tls_setting.ciphers_num++] = cipher;
+		    cfg->udp_cfg.tls_setting.ciphers = tls_ciphers;
+		} else {
+		    pj_ssl_cipher ciphers[128];
+		    unsigned j, ciphers_cnt;
+
+		    ciphers_cnt = PJ_ARRAY_SIZE(ciphers);
+		    pj_ssl_cipher_get_availables(ciphers, &ciphers_cnt);
+		    
+		    PJ_LOG(1,(THIS_FILE, "Cipher \"%s\" is not supported by "
+					 "TLS/SSL backend.", pj_optarg));
+		    printf("Available TLS/SSL ciphers (%d):\n", ciphers_cnt);
+		    for (j=0; j<ciphers_cnt; ++j)
+			printf("- 0x%06X: %s\n", ciphers[j], pj_ssl_cipher_name(ciphers[j]));
+		    return -1;
+		}
+	    }
+ 	    break;
+#endif /* PJSIP_HAS_TLS_TRANSPORT */
+
+	case OPT_CAPTURE_DEV:
+	    cfg->capture_dev = atoi(pj_optarg);
+	    break;
+
+	case OPT_PLAYBACK_DEV:
+	    cfg->playback_dev = atoi(pj_optarg);
+	    break;
+
+	case OPT_STDOUT_REFRESH:
+	    stdout_refresh = atoi(pj_optarg);
+	    break;
+
+	case OPT_STDOUT_REFRESH_TEXT:
+	    stdout_refresh_text = pj_optarg;
+	    break;
+
+#ifdef _IONBF
+	case OPT_STDOUT_NO_BUF:
+	    setvbuf(stdout, NULL, _IONBF, 0);
+	    break;
+#endif
+
+	case OPT_CAPTURE_LAT:
+	    cfg->capture_lat = atoi(pj_optarg);
+	    break;
+
+	case OPT_PLAYBACK_LAT:
+	    cfg->playback_lat = atoi(pj_optarg);
+	    break;
+
+	case OPT_SND_AUTO_CLOSE:
+	    cfg->media_cfg.snd_auto_close_time = atoi(pj_optarg);
+	    break;
+
+	case OPT_NO_TONES:
+	    cfg->no_tones = PJ_TRUE;
+	    break;
+
+	case OPT_JB_MAX_SIZE:
+	    cfg->media_cfg.jb_max = atoi(pj_optarg);
+	    break;
+
+#if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6
+	case OPT_IPV6:
+	    cfg->ipv6 = PJ_TRUE;
+	    break;
+#endif
+	case OPT_QOS:
+	    cfg->enable_qos = PJ_TRUE;
+	    /* Set RTP traffic type to Voice */
+	    cfg->rtp_cfg.qos_type = PJ_QOS_TYPE_VOICE;
+	    /* Directly apply DSCP value to SIP traffic. Say lets
+	     * set it to CS3 (DSCP 011000). Note that this will not 
+	     * work on all platforms.
+	     */
+	    cfg->udp_cfg.qos_params.flags = PJ_QOS_PARAM_HAS_DSCP;
+	    cfg->udp_cfg.qos_params.dscp_val = 0x18;
+	    break;
+	case OPT_VIDEO:
+	    cfg->vid.vid_cnt = 1;
+	    cfg->vid.in_auto_show = PJ_TRUE;
+	    cfg->vid.out_auto_transmit = PJ_TRUE;
+	    break;
+	case OPT_EXTRA_AUDIO:
+	    cfg->aud_cnt++;
+	    break;
+
+	case OPT_VCAPTURE_DEV:
+	    cfg->vid.vcapture_dev = atoi(pj_optarg);
+	    cur_acc->vid_cap_dev = cfg->vid.vcapture_dev;
+	    break;
+
+	case OPT_VRENDER_DEV:
+	    cfg->vid.vrender_dev = atoi(pj_optarg);
+	    cur_acc->vid_rend_dev = cfg->vid.vrender_dev;
+	    break;
+
+	case OPT_PLAY_AVI:
+	    if (app_config.avi_cnt >= MAX_AVI) {
+		PJ_LOG(1,(THIS_FILE, "Too many AVIs"));
+		return -1;
+	    }
+	    app_config.avi[app_config.avi_cnt++].path = pj_str(pj_optarg);
+	    break;
+
+	case OPT_AUTO_PLAY_AVI:
+	    app_config.avi_auto_play = PJ_TRUE;
+	    break;
+
+	case OPT_USE_CLI:
+	    cfg->use_cli = PJ_TRUE;
+	    break;
+
+	case OPT_CLI_TELNET_PORT:
+	    cfg->cli_telnet_port = atoi(pj_optarg);
+	    break;
+
+	case OPT_DISABLE_CLI_CONSOLE:
+	    cfg->disable_cli_console = PJ_TRUE;
+	    break;
+
+	default:
+	    PJ_LOG(1,(THIS_FILE, 
+		      "Argument \"%s\" is not valid. Use --help to see help",
+		      argv[pj_optind-1]));
+	    return -1;
+	}
+    }
+
+    if (pj_optind != argc) {
+	pj_str_t uri_arg;
+
+	if (pjsua_verify_url(argv[pj_optind]) != PJ_SUCCESS) {
+	    PJ_LOG(1,(THIS_FILE, "Invalid SIP URI %s", argv[pj_optind]));
+	    return -1;
+	}
+	uri_arg = pj_str(argv[pj_optind]);
+	if (uri_to_call)
+	    *uri_to_call = uri_arg;
+	pj_optind++;
+
+	/* Add URI to call to buddy list if it's not already there */
+	for (i=0; i<cfg->buddy_cnt; ++i) {
+	    if (pj_stricmp(&cfg->buddy_cfg[i].uri, &uri_arg)==0)
+		break;
+	}
+	if (i == cfg->buddy_cnt && cfg->buddy_cnt < PJSUA_MAX_BUDDIES) {
+	    cfg->buddy_cfg[cfg->buddy_cnt++].uri = uri_arg;
+	}
+
+    } else {
+	if (uri_to_call)
+	    uri_to_call->slen = 0;
+    }
+
+    if (pj_optind != argc) {
+	PJ_LOG(1,(THIS_FILE, "Error: unknown options %s", argv[pj_optind]));
+	return PJ_EINVAL;
+    }
+
+    if (cfg->acc_cfg[cfg->acc_cnt].id.slen)
+	cfg->acc_cnt++;
+
+    for (i=0; i<cfg->acc_cnt; ++i) {
+	pjsua_acc_config *acfg = &cfg->acc_cfg[i];
+
+	if (acfg->cred_info[acfg->cred_count].username.slen)
+	{
+	    acfg->cred_count++;
+	}
+
+	if (acfg->ice_cfg.enable_ice) {
+	    acfg->ice_cfg_use = PJSUA_ICE_CONFIG_USE_CUSTOM;
+	}
+	if (acfg->turn_cfg.enable_turn) {
+	    acfg->turn_cfg_use = PJSUA_TURN_CONFIG_USE_CUSTOM;
+	}
+
+	/* When IMS mode is enabled for the account, verify that settings
+	 * are okay.
+	 */
+	/* For now we check if IMS mode is activated by looking if
+	 * initial_auth is set.
+	 */
+	if (acfg->auth_pref.initial_auth && acfg->cred_count) {
+	    /* Realm must point to the real domain */
+	    if (*acfg->cred_info[0].realm.ptr=='*') {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: cannot use '*' as realm with IMS"));
+		return PJ_EINVAL;
+	    }
+
+	    /* Username for authentication must be in a@b format */
+	    if (strchr(acfg->cred_info[0].username.ptr, '@')==0) {
+		PJ_LOG(1,(THIS_FILE, 
+			  "Error: Username for authentication must "
+			  "be in user@domain format with IMS"));
+		return PJ_EINVAL;
+	    }
+	}
+    }
+    return PJ_SUCCESS;
+}
+
+/* Set default config. */
+static void default_config(pjsua_app_config *cfg)
+{
+    char tmp[80];
+    unsigned i;
+
+    pjsua_config_default(&cfg->cfg);
+    pj_ansi_sprintf(tmp, "PJSUA v%s %s", pj_get_version(),
+		    pj_get_sys_info()->info.ptr);
+    pj_strdup2_with_null(app_config.pool, &cfg->cfg.user_agent, tmp);
+
+    pjsua_logging_config_default(&cfg->log_cfg);
+    pjsua_media_config_default(&cfg->media_cfg);
+    pjsua_transport_config_default(&cfg->udp_cfg);
+    cfg->udp_cfg.port = 5060;
+    pjsua_transport_config_default(&cfg->rtp_cfg);
+    cfg->rtp_cfg.port = 4000;
+    cfg->redir_op = PJSIP_REDIRECT_ACCEPT_REPLACE;
+    cfg->duration = NO_LIMIT_DURATION;
+    cfg->wav_id = PJSUA_INVALID_ID;
+    cfg->rec_id = PJSUA_INVALID_ID;
+    cfg->wav_port = PJSUA_INVALID_ID;
+    cfg->rec_port = PJSUA_INVALID_ID;
+    cfg->mic_level = cfg->speaker_level = 1.0;
+    cfg->capture_dev = PJSUA_INVALID_ID;
+    cfg->playback_dev = PJSUA_INVALID_ID;
+    cfg->capture_lat = PJMEDIA_SND_DEFAULT_REC_LATENCY;
+    cfg->playback_lat = PJMEDIA_SND_DEFAULT_PLAY_LATENCY;
+    cfg->ringback_slot = PJSUA_INVALID_ID;
+    cfg->ring_slot = PJSUA_INVALID_ID;
+
+    for (i=0; i<PJ_ARRAY_SIZE(cfg->acc_cfg); ++i)
+	pjsua_acc_config_default(&cfg->acc_cfg[i]);
+
+    for (i=0; i<PJ_ARRAY_SIZE(cfg->buddy_cfg); ++i)
+	pjsua_buddy_config_default(&cfg->buddy_cfg[i]);
+
+    cfg->vid.vcapture_dev = PJMEDIA_VID_DEFAULT_CAPTURE_DEV;
+    cfg->vid.vrender_dev = PJMEDIA_VID_DEFAULT_RENDER_DEV;
+    cfg->aud_cnt = 1;
+
+    cfg->avi_def_idx = PJSUA_INVALID_ID;
+
+    cfg->use_cli = PJ_FALSE;
+    cfg->disable_cli_console = PJ_FALSE;
+    cfg->cli_telnet_port = -1;
+}
+
+static pj_status_t parse_config(int argc, char *argv[], 
+				pjsua_app_config *app_config, pj_str_t *uri_arg)
+{
+    pj_status_t status;
+
+    /* Initialize default config */
+    default_config(app_config);
+
+    /* Parse the arguments */
+    status = parse_args(argc, argv, app_config, uri_arg);
+    return status;
+}
+
+PJ_DEF(void) add_startup_config(int argc, char *argv[])
+{
+    int i;
+    cmd_argc = argc;
+
+    for (i=0;i<argc;++i)
+    {
+	pj_memcpy(&cmd_argv[i], argv[i], strlen(argv[i]));
+	cmd_argv[i][strlen(argv[i])] = 0;
+    }    
+}
+
+PJ_DEF(void) add_reload_config(unsigned idx, pj_str_t *option)
+{        
+    /** First command always contain the app path**/
+    pj_str_t cmd;
+    
+    pj_assert(idx < MAX_APP_OPTIONS);
+
+    cmd = pj_str(&cmd_argv[idx][0]);
+    pj_strncpy_with_null(&cmd, option, 128);    
+    cmd_argc = idx+1;
+}
+
+PJ_DEF(pj_status_t) load_config(pjsua_app_config *app_config, 
+				pj_str_t *uri_arg,
+				pj_bool_t app_running)
+{
+    int i;
+    int argc = cmd_argc;
+    char *argv[128];
+    pj_status_t status;
+    pj_bool_t use_cli = PJ_FALSE;
+    pj_bool_t disable_cli_console = PJ_TRUE;
+    int cli_telnet_port = 0;
+
+    /** CLI options are not changable **/
+    if (app_running) {
+	use_cli = app_config->use_cli;
+	disable_cli_console = app_config->disable_cli_console;
+	cli_telnet_port = app_config->cli_telnet_port;
+    }
+
+    for (i=0;i<cmd_argc;++i)
+    {
+	argv[i] = &cmd_argv[i][0];
+    }
+
+    status = parse_config(argc, argv, app_config, uri_arg);
+    if (status != PJ_SUCCESS)
+	return status;
+
+    if (app_running) {    
+	app_config->use_cli = use_cli;
+	app_config->disable_cli_console = disable_cli_console;
+	app_config->cli_telnet_port = cli_telnet_port;
+    }
+
+    return status;
+}
+
+/*
+ * Save account settings
+ */
+static void write_account_settings(int acc_index, pj_str_t *result)
+{
+    unsigned i;
+    char line[128];
+    pjsua_acc_config *acc_cfg = &app_config.acc_cfg[acc_index];
+
+
+    pj_ansi_sprintf(line, "\n#\n# Account %d:\n#\n", acc_index);
+    pj_strcat2(result, line);
+
+
+    /* Identity */
+    if (acc_cfg->id.slen) {
+	pj_ansi_sprintf(line, "--id %.*s\n",
+			(int)acc_cfg->id.slen,
+			acc_cfg->id.ptr);
+	pj_strcat2(result, line);
+    }
+
+    /* Registrar server */
+    if (acc_cfg->reg_uri.slen) {
+	pj_ansi_sprintf(line, "--registrar %.*s\n",
+			      (int)acc_cfg->reg_uri.slen,
+			      acc_cfg->reg_uri.ptr);
+	pj_strcat2(result, line);
+
+	pj_ansi_sprintf(line, "--reg-timeout %u\n",
+			      acc_cfg->reg_timeout);
+	pj_strcat2(result, line);
+    }
+
+    /* Contact */
+    if (acc_cfg->force_contact.slen) {
+	pj_ansi_sprintf(line, "--contact %.*s\n",
+			(int)acc_cfg->force_contact.slen,
+			acc_cfg->force_contact.ptr);
+	pj_strcat2(result, line);
+    }
+
+    /* Contact header parameters */
+    if (acc_cfg->contact_params.slen) {
+	pj_ansi_sprintf(line, "--contact-params %.*s\n",
+			(int)acc_cfg->contact_params.slen,
+			acc_cfg->contact_params.ptr);
+	pj_strcat2(result, line);
+    }
+
+    /* Contact URI parameters */
+    if (acc_cfg->contact_uri_params.slen) {
+	pj_ansi_sprintf(line, "--contact-uri-params %.*s\n",
+			(int)acc_cfg->contact_uri_params.slen,
+			acc_cfg->contact_uri_params.ptr);
+	pj_strcat2(result, line);
+    }
+
+    /*  */
+    if (acc_cfg->allow_contact_rewrite!=1)
+    {
+	pj_ansi_sprintf(line, "--auto-update-nat %i\n",
+			(int)acc_cfg->allow_contact_rewrite);
+	pj_strcat2(result, line);
+    }
+
+#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
+    /* SRTP */
+    if (acc_cfg->use_srtp) {
+	int use_srtp = (int)acc_cfg->use_srtp;
+	if (use_srtp == PJMEDIA_SRTP_OPTIONAL &&
+	    acc_cfg->srtp_optional_dup_offer)
+	{
+	    use_srtp = 3;
+	}
+	pj_ansi_sprintf(line, "--use-srtp %i\n", use_srtp);
+	pj_strcat2(result, line);
+    }
+    if (acc_cfg->srtp_secure_signaling !=
+	PJSUA_DEFAULT_SRTP_SECURE_SIGNALING)
+    {
+	pj_ansi_sprintf(line, "--srtp-secure %d\n",
+			acc_cfg->srtp_secure_signaling);
+	pj_strcat2(result, line);
+    }
+#endif
+
+    /* Proxy */
+    for (i=0; i<acc_cfg->proxy_cnt; ++i) {
+	pj_ansi_sprintf(line, "--proxy %.*s\n",
+			      (int)acc_cfg->proxy[i].slen,
+			      acc_cfg->proxy[i].ptr);
+	pj_strcat2(result, line);
+    }
+
+    /* Credentials */
+    for (i=0; i<acc_cfg->cred_count; ++i) {
+	if (acc_cfg->cred_info[i].realm.slen) {
+	    pj_ansi_sprintf(line, "--realm %.*s\n",
+				  (int)acc_cfg->cred_info[i].realm.slen,
+				  acc_cfg->cred_info[i].realm.ptr);
+	    pj_strcat2(result, line);
+	}
+
+	if (acc_cfg->cred_info[i].username.slen) {
+	    pj_ansi_sprintf(line, "--username %.*s\n",
+				  (int)acc_cfg->cred_info[i].username.slen,
+				  acc_cfg->cred_info[i].username.ptr);
+	    pj_strcat2(result, line);
+	}
+
+	if (acc_cfg->cred_info[i].data.slen) {
+	    pj_ansi_sprintf(line, "--password %.*s\n",
+				  (int)acc_cfg->cred_info[i].data.slen,
+				  acc_cfg->cred_info[i].data.ptr);
+	    pj_strcat2(result, line);
+	}
+
+	if (i != acc_cfg->cred_count - 1)
+	    pj_strcat2(result, "--next-cred\n");
+    }
+
+    /* reg-use-proxy */
+    if (acc_cfg->reg_use_proxy != 3) {
+	pj_ansi_sprintf(line, "--reg-use-proxy %d\n",
+			      acc_cfg->reg_use_proxy);
+	pj_strcat2(result, line);
+    }
+
+    /* rereg-delay */
+    if (acc_cfg->reg_retry_interval != PJSUA_REG_RETRY_INTERVAL) {
+	pj_ansi_sprintf(line, "--rereg-delay %d\n",
+		              acc_cfg->reg_retry_interval);
+	pj_strcat2(result, line);
+    }
+
+    /* 100rel extension */
+    if (acc_cfg->require_100rel) {
+	pj_strcat2(result, "--use-100rel\n");
+    }
+
+    /* Session Timer extension */
+    if (acc_cfg->use_timer) {
+	pj_ansi_sprintf(line, "--use-timer %d\n",
+			      acc_cfg->use_timer);
+	pj_strcat2(result, line);
+    }
+    if (acc_cfg->timer_setting.min_se != 90) {
+	pj_ansi_sprintf(line, "--timer-min-se %d\n",
+			      acc_cfg->timer_setting.min_se);
+	pj_strcat2(result, line);
+    }
+    if (acc_cfg->timer_setting.sess_expires != PJSIP_SESS_TIMER_DEF_SE) {
+	pj_ansi_sprintf(line, "--timer-se %d\n",
+			      acc_cfg->timer_setting.sess_expires);
+	pj_strcat2(result, line);
+    }
+
+    /* Publish */
+    if (acc_cfg->publish_enabled)
+	pj_strcat2(result, "--publish\n");
+
+    /* MWI */
+    if (acc_cfg->mwi_enabled)
+	pj_strcat2(result, "--mwi\n");
+
+    if (acc_cfg->sip_stun_use != PJSUA_STUN_USE_DEFAULT ||
+	acc_cfg->media_stun_use != PJSUA_STUN_USE_DEFAULT)
+    {
+	pj_strcat2(result, "--disable-stun\n");
+    }
+
+    /* Media Transport*/
+    if (acc_cfg->ice_cfg.enable_ice)
+	pj_strcat2(result, "--use-ice\n");
+
+    if (acc_cfg->ice_cfg.ice_opt.aggressive == PJ_FALSE)
+	pj_strcat2(result, "--ice-regular\n");
+
+    if (acc_cfg->turn_cfg.enable_turn)
+	pj_strcat2(result, "--use-turn\n");
+
+    if (acc_cfg->ice_cfg.ice_max_host_cands >= 0) {
+	pj_ansi_sprintf(line, "--ice_max_host_cands %d\n",
+	                acc_cfg->ice_cfg.ice_max_host_cands);
+	pj_strcat2(result, line);
+    }
+
+    if (acc_cfg->ice_cfg.ice_no_rtcp)
+	pj_strcat2(result, "--ice-no-rtcp\n");
+
+    if (acc_cfg->turn_cfg.turn_server.slen) {
+	pj_ansi_sprintf(line, "--turn-srv %.*s\n",
+			(int)acc_cfg->turn_cfg.turn_server.slen,
+			acc_cfg->turn_cfg.turn_server.ptr);
+	pj_strcat2(result, line);
+    }
+
+    if (acc_cfg->turn_cfg.turn_conn_type == PJ_TURN_TP_TCP)
+	pj_strcat2(result, "--turn-tcp\n");
+
+    if (acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.slen) {
+	pj_ansi_sprintf(line, "--turn-user %.*s\n",
+			(int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.slen,
+			acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.username.ptr);
+	pj_strcat2(result, line);
+    }
+
+    if (acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.slen) {
+	pj_ansi_sprintf(line, "--turn-passwd %.*s\n",
+			(int)acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.slen,
+			acc_cfg->turn_cfg.turn_auth_cred.data.static_cred.data.ptr);
+	pj_strcat2(result, line);
+    }
+}
+
+/*
+ * Write settings.
+ */
+PJ_DEF(int) write_settings(pjsua_app_config *config, char *buf, pj_size_t max)
+{
+    unsigned acc_index;
+    unsigned i;
+    pj_str_t cfg;
+    char line[128];
+    extern pj_bool_t pjsip_use_compact_form;
+
+    PJ_UNUSED_ARG(max);
+
+    cfg.ptr = buf;
+    cfg.slen = 0;
+
+    /* Logging. */
+    pj_strcat2(&cfg, "#\n# Logging options:\n#\n");
+    pj_ansi_sprintf(line, "--log-level %d\n",
+		    config->log_cfg.level);
+    pj_strcat2(&cfg, line);
+
+    pj_ansi_sprintf(line, "--app-log-level %d\n",
+		    config->log_cfg.console_level);
+    pj_strcat2(&cfg, line);
+
+    if (config->log_cfg.log_filename.slen) {
+	pj_ansi_sprintf(line, "--log-file %.*s\n",
+			(int)config->log_cfg.log_filename.slen,
+			config->log_cfg.log_filename.ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    if (config->log_cfg.log_file_flags & PJ_O_APPEND) {
+	pj_strcat2(&cfg, "--log-append\n");
+    }
+
+    /* Save account settings. */
+    for (acc_index=0; acc_index < config->acc_cnt; ++acc_index) {
+
+	write_account_settings(acc_index, &cfg);
+
+	if (acc_index < config->acc_cnt-1)
+	    pj_strcat2(&cfg, "--next-account\n");
+    }
+
+    pj_strcat2(&cfg, "\n#\n# Network settings:\n#\n");
+
+    /* Nameservers */
+    for (i=0; i<config->cfg.nameserver_count; ++i) {
+	pj_ansi_sprintf(line, "--nameserver %.*s\n",
+			      (int)config->cfg.nameserver[i].slen,
+			      config->cfg.nameserver[i].ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* Outbound proxy */
+    for (i=0; i<config->cfg.outbound_proxy_cnt; ++i) {
+	pj_ansi_sprintf(line, "--outbound %.*s\n",
+			      (int)config->cfg.outbound_proxy[i].slen,
+			      config->cfg.outbound_proxy[i].ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* Transport options */
+    if (config->ipv6) {
+	pj_strcat2(&cfg, "--ipv6\n");
+    }
+    if (config->enable_qos) {
+	pj_strcat2(&cfg, "--set-qos\n");
+    }
+
+    /* UDP Transport. */
+    pj_ansi_sprintf(line, "--local-port %d\n", config->udp_cfg.port);
+    pj_strcat2(&cfg, line);
+
+    /* IP address, if any. */
+    if (config->udp_cfg.public_addr.slen) {
+	pj_ansi_sprintf(line, "--ip-addr %.*s\n",
+			(int)config->udp_cfg.public_addr.slen,
+			config->udp_cfg.public_addr.ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* Bound IP address, if any. */
+    if (config->udp_cfg.bound_addr.slen) {
+	pj_ansi_sprintf(line, "--bound-addr %.*s\n",
+			(int)config->udp_cfg.bound_addr.slen,
+			config->udp_cfg.bound_addr.ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* No TCP ? */
+    if (config->no_tcp) {
+	pj_strcat2(&cfg, "--no-tcp\n");
+    }
+
+    /* No UDP ? */
+    if (config->no_udp) {
+	pj_strcat2(&cfg, "--no-udp\n");
+    }
+
+    /* STUN */
+    for (i=0; i<config->cfg.stun_srv_cnt; ++i) {
+	pj_ansi_sprintf(line, "--stun-srv %.*s\n",
+			(int)config->cfg.stun_srv[i].slen,
+			config->cfg.stun_srv[i].ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+#if defined(PJSIP_HAS_TLS_TRANSPORT) && (PJSIP_HAS_TLS_TRANSPORT != 0)
+    /* TLS */
+    if (config->use_tls)
+	pj_strcat2(&cfg, "--use-tls\n");
+    if (config->udp_cfg.tls_setting.ca_list_file.slen) {
+	pj_ansi_sprintf(line, "--tls-ca-file %.*s\n",
+			(int)config->udp_cfg.tls_setting.ca_list_file.slen,
+			config->udp_cfg.tls_setting.ca_list_file.ptr);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->udp_cfg.tls_setting.cert_file.slen) {
+	pj_ansi_sprintf(line, "--tls-cert-file %.*s\n",
+			(int)config->udp_cfg.tls_setting.cert_file.slen,
+			config->udp_cfg.tls_setting.cert_file.ptr);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->udp_cfg.tls_setting.privkey_file.slen) {
+	pj_ansi_sprintf(line, "--tls-privkey-file %.*s\n",
+			(int)config->udp_cfg.tls_setting.privkey_file.slen,
+			config->udp_cfg.tls_setting.privkey_file.ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    if (config->udp_cfg.tls_setting.password.slen) {
+	pj_ansi_sprintf(line, "--tls-password %.*s\n",
+			(int)config->udp_cfg.tls_setting.password.slen,
+			config->udp_cfg.tls_setting.password.ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    if (config->udp_cfg.tls_setting.verify_server)
+	pj_strcat2(&cfg, "--tls-verify-server\n");
+
+    if (config->udp_cfg.tls_setting.verify_client)
+	pj_strcat2(&cfg, "--tls-verify-client\n");
+
+    if (config->udp_cfg.tls_setting.timeout.sec) {
+	pj_ansi_sprintf(line, "--tls-neg-timeout %d\n",
+			(int)config->udp_cfg.tls_setting.timeout.sec);
+	pj_strcat2(&cfg, line);
+    }
+
+    for (i=0; i<config->udp_cfg.tls_setting.ciphers_num; ++i) {
+	pj_ansi_sprintf(line, "--tls-cipher 0x%06X # %s\n",
+			config->udp_cfg.tls_setting.ciphers[i],
+			pj_ssl_cipher_name(config->udp_cfg.tls_setting.ciphers[i]));
+	pj_strcat2(&cfg, line);
+    }
+#endif
+
+    pj_strcat2(&cfg, "\n#\n# Media settings:\n#\n");
+
+    /* Video & extra audio */
+    for (i=0; i<config->vid.vid_cnt; ++i) {
+	pj_strcat2(&cfg, "--video\n");
+    }
+    for (i=1; i<config->aud_cnt; ++i) {
+	pj_strcat2(&cfg, "--extra-audio\n");
+    }
+
+    /* SRTP */
+#if PJMEDIA_HAS_SRTP
+    if (app_config.cfg.use_srtp != PJSUA_DEFAULT_USE_SRTP) {
+	int use_srtp = (int)app_config.cfg.use_srtp;
+	if (use_srtp == PJMEDIA_SRTP_OPTIONAL &&
+	    app_config.cfg.srtp_optional_dup_offer)
+	{
+	    use_srtp = 3;
+	}
+	pj_ansi_sprintf(line, "--use-srtp %d\n", use_srtp);
+	pj_strcat2(&cfg, line);
+    }
+    if (app_config.cfg.srtp_secure_signaling !=
+	PJSUA_DEFAULT_SRTP_SECURE_SIGNALING)
+    {
+	pj_ansi_sprintf(line, "--srtp-secure %d\n",
+			app_config.cfg.srtp_secure_signaling);
+	pj_strcat2(&cfg, line);
+    }
+#endif
+
+    /* Media */
+    if (config->null_audio)
+	pj_strcat2(&cfg, "--null-audio\n");
+    if (config->auto_play)
+	pj_strcat2(&cfg, "--auto-play\n");
+    if (config->auto_loop)
+	pj_strcat2(&cfg, "--auto-loop\n");
+    if (config->auto_conf)
+	pj_strcat2(&cfg, "--auto-conf\n");
+    for (i=0; i<config->wav_count; ++i) {
+	pj_ansi_sprintf(line, "--play-file %s\n",
+			config->wav_files[i].ptr);
+	pj_strcat2(&cfg, line);
+    }
+    for (i=0; i<config->tone_count; ++i) {
+	pj_ansi_sprintf(line, "--play-tone %d,%d,%d,%d\n",
+			config->tones[i].freq1, config->tones[i].freq2,
+			config->tones[i].on_msec, config->tones[i].off_msec);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->rec_file.slen) {
+	pj_ansi_sprintf(line, "--rec-file %s\n",
+			config->rec_file.ptr);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->auto_rec)
+	pj_strcat2(&cfg, "--auto-rec\n");
+    if (config->capture_dev != PJSUA_INVALID_ID) {
+	pj_ansi_sprintf(line, "--capture-dev %d\n", config->capture_dev);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->playback_dev != PJSUA_INVALID_ID) {
+	pj_ansi_sprintf(line, "--playback-dev %d\n", config->playback_dev);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->media_cfg.snd_auto_close_time != -1) {
+	pj_ansi_sprintf(line, "--snd-auto-close %d\n",
+			config->media_cfg.snd_auto_close_time);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->no_tones) {
+	pj_strcat2(&cfg, "--no-tones\n");
+    }
+    if (config->media_cfg.jb_max != -1) {
+	pj_ansi_sprintf(line, "--jb-max-size %d\n",
+			config->media_cfg.jb_max);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* Sound device latency */
+    if (config->capture_lat != PJMEDIA_SND_DEFAULT_REC_LATENCY) {
+	pj_ansi_sprintf(line, "--capture-lat %d\n", config->capture_lat);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->playback_lat != PJMEDIA_SND_DEFAULT_PLAY_LATENCY) {
+	pj_ansi_sprintf(line, "--playback-lat %d\n", config->playback_lat);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* Media clock rate. */
+    if (config->media_cfg.clock_rate != PJSUA_DEFAULT_CLOCK_RATE) {
+	pj_ansi_sprintf(line, "--clock-rate %d\n",
+			config->media_cfg.clock_rate);
+	pj_strcat2(&cfg, line);
+    } else {
+	pj_ansi_sprintf(line, "#using default --clock-rate %d\n",
+			config->media_cfg.clock_rate);
+	pj_strcat2(&cfg, line);
+    }
+
+    if (config->media_cfg.snd_clock_rate &&
+	config->media_cfg.snd_clock_rate != config->media_cfg.clock_rate)
+    {
+	pj_ansi_sprintf(line, "--snd-clock-rate %d\n",
+			config->media_cfg.snd_clock_rate);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* Stereo mode. */
+    if (config->media_cfg.channel_count == 2) {
+	pj_ansi_sprintf(line, "--stereo\n");
+	pj_strcat2(&cfg, line);
+    }
+
+    /* quality */
+    if (config->media_cfg.quality != PJSUA_DEFAULT_CODEC_QUALITY) {
+	pj_ansi_sprintf(line, "--quality %d\n",
+			config->media_cfg.quality);
+	pj_strcat2(&cfg, line);
+    } else {
+	pj_ansi_sprintf(line, "#using default --quality %d\n",
+			config->media_cfg.quality);
+	pj_strcat2(&cfg, line);
+    }
+
+    if (config->vid.vcapture_dev != PJMEDIA_VID_DEFAULT_CAPTURE_DEV) {
+	pj_ansi_sprintf(line, "--vcapture-dev %d\n", config->vid.vcapture_dev);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->vid.vrender_dev != PJMEDIA_VID_DEFAULT_RENDER_DEV) {
+	pj_ansi_sprintf(line, "--vrender-dev %d\n", config->vid.vrender_dev);
+	pj_strcat2(&cfg, line);
+    }
+    for (i=0; i<config->avi_cnt; ++i) {
+	pj_ansi_sprintf(line, "--play-avi %s\n", config->avi[i].path.ptr);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->avi_auto_play) {
+	pj_ansi_sprintf(line, "--auto-play-avi\n");
+	pj_strcat2(&cfg, line);
+    }
+
+    /* ptime */
+    if (config->media_cfg.ptime) {
+	pj_ansi_sprintf(line, "--ptime %d\n",
+			config->media_cfg.ptime);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* no-vad */
+    if (config->media_cfg.no_vad) {
+	pj_strcat2(&cfg, "--no-vad\n");
+    }
+
+    /* ec-tail */
+    if (config->media_cfg.ec_tail_len != PJSUA_DEFAULT_EC_TAIL_LEN) {
+	pj_ansi_sprintf(line, "--ec-tail %d\n",
+			config->media_cfg.ec_tail_len);
+	pj_strcat2(&cfg, line);
+    } else {
+	pj_ansi_sprintf(line, "#using default --ec-tail %d\n",
+			config->media_cfg.ec_tail_len);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* ec-opt */
+    if (config->media_cfg.ec_options != 0) {
+	pj_ansi_sprintf(line, "--ec-opt %d\n",
+			config->media_cfg.ec_options);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* ilbc-mode */
+    if (config->media_cfg.ilbc_mode != PJSUA_DEFAULT_ILBC_MODE) {
+	pj_ansi_sprintf(line, "--ilbc-mode %d\n",
+			config->media_cfg.ilbc_mode);
+	pj_strcat2(&cfg, line);
+    } else {
+	pj_ansi_sprintf(line, "#using default --ilbc-mode %d\n",
+			config->media_cfg.ilbc_mode);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* RTP drop */
+    if (config->media_cfg.tx_drop_pct) {
+	pj_ansi_sprintf(line, "--tx-drop-pct %d\n",
+			config->media_cfg.tx_drop_pct);
+	pj_strcat2(&cfg, line);
+
+    }
+    if (config->media_cfg.rx_drop_pct) {
+	pj_ansi_sprintf(line, "--rx-drop-pct %d\n",
+			config->media_cfg.rx_drop_pct);
+	pj_strcat2(&cfg, line);
+
+    }
+
+    /* Start RTP port. */
+    pj_ansi_sprintf(line, "--rtp-port %d\n",
+		    config->rtp_cfg.port);
+    pj_strcat2(&cfg, line);
+
+    /* Disable codec */
+    for (i=0; i<config->codec_dis_cnt; ++i) {
+	pj_ansi_sprintf(line, "--dis-codec %s\n",
+		    config->codec_dis[i].ptr);
+	pj_strcat2(&cfg, line);
+    }
+    /* Add codec. */
+    for (i=0; i<config->codec_cnt; ++i) {
+	pj_ansi_sprintf(line, "--add-codec %s\n",
+		    config->codec_arg[i].ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    pj_strcat2(&cfg, "\n#\n# User agent:\n#\n");
+
+    /* Auto-answer. */
+    if (config->auto_answer != 0) {
+	pj_ansi_sprintf(line, "--auto-answer %d\n",
+			config->auto_answer);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* accept-redirect */
+    if (config->redir_op != PJSIP_REDIRECT_ACCEPT_REPLACE) {
+	pj_ansi_sprintf(line, "--accept-redirect %d\n",
+			config->redir_op);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* Max calls. */
+    pj_ansi_sprintf(line, "--max-calls %d\n",
+		    config->cfg.max_calls);
+    pj_strcat2(&cfg, line);
+
+    /* Uas-duration. */
+    if (config->duration != NO_LIMIT_DURATION) {
+	pj_ansi_sprintf(line, "--duration %d\n",
+			config->duration);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* norefersub ? */
+    if (config->no_refersub) {
+	pj_strcat2(&cfg, "--norefersub\n");
+    }
+
+    if (pjsip_use_compact_form)
+    {
+	pj_strcat2(&cfg, "--use-compact-form\n");
+    }
+
+    if (!config->cfg.force_lr) {
+	pj_strcat2(&cfg, "--no-force-lr\n");
+    }
+
+    pj_strcat2(&cfg, "\n#\n# Buddies:\n#\n");
+
+    /* Add buddies. */
+    for (i=0; i<config->buddy_cnt; ++i) {
+	pj_ansi_sprintf(line, "--add-buddy %.*s\n",
+			      (int)config->buddy_cfg[i].uri.slen,
+			      config->buddy_cfg[i].uri.ptr);
+	pj_strcat2(&cfg, line);
+    }
+
+    /* SIP extensions. */
+    pj_strcat2(&cfg, "\n#\n# SIP extensions:\n#\n");
+    /* 100rel extension */
+    if (config->cfg.require_100rel) {
+	pj_strcat2(&cfg, "--use-100rel\n");
+    }
+    /* Session Timer extension */
+    if (config->cfg.use_timer) {
+	pj_ansi_sprintf(line, "--use-timer %d\n",
+			      config->cfg.use_timer);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->cfg.timer_setting.min_se != 90) {
+	pj_ansi_sprintf(line, "--timer-min-se %d\n",
+			      config->cfg.timer_setting.min_se);
+	pj_strcat2(&cfg, line);
+    }
+    if (config->cfg.timer_setting.sess_expires != PJSIP_SESS_TIMER_DEF_SE) {
+	pj_ansi_sprintf(line, "--timer-se %d\n",
+			      config->cfg.timer_setting.sess_expires);
+	pj_strcat2(&cfg, line);
+    }
+
+    *(cfg.ptr + cfg.slen) = '\0';
+    return cfg.slen;
+}
Index: /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_legacy.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_legacy.c	(revision 4461)
+++ /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_legacy.c	(revision 4461)
@@ -0,0 +1,1959 @@
+/* $Id$ */
+/* 
+ * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
+ * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.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 
+ */
+
+#include <pjsua-lib/pjsua.h>
+#include "pjsua_common.h"
+#include "gui.h"
+
+#define THIS_FILE	"pjsua_legacy.c"
+
+static pj_bool_t	cmd_echo;
+
+/*
+ * Print buddy list.
+ */
+static void print_buddy_list()
+{
+    pjsua_buddy_id ids[64];
+    int i;
+    unsigned count = PJ_ARRAY_SIZE(ids);
+
+    puts("Buddy list:");
+
+    pjsua_enum_buddies(ids, &count);
+
+    if (count == 0)
+	puts(" -none-");
+    else {
+	for (i=0; i<(int)count; ++i) {
+	    pjsua_buddy_info info;
+
+	    if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS)
+		continue;
+
+	    printf(" [%2d] <%.*s>  %.*s\n", 
+		    ids[i]+1, 
+		    (int)info.status_text.slen,
+		    info.status_text.ptr, 
+		    (int)info.uri.slen,
+		    info.uri.ptr);
+	}
+    }
+    puts("");
+}
+
+/*
+ * Input URL.
+ */
+static void ui_input_url(const char *title, char *buf, int len, 
+			 input_result *result)
+{
+    result->nb_result = NO_NB;
+    result->uri_result = NULL;
+
+    print_buddy_list();
+
+    printf("Choices:\n"
+	   "   0         For current dialog.\n"
+	   "  -1         All %d buddies in buddy list\n"
+	   "  [1 -%2d]    Select from buddy list\n"
+	   "  URL        An URL\n"
+	   "  <Enter>    Empty input (or 'q') to cancel\n"
+	   , pjsua_get_buddy_count(), pjsua_get_buddy_count());
+    printf("%s: ", title);
+
+    fflush(stdout);
+    if (fgets(buf, len, stdin) == NULL)
+	return;
+    len = strlen(buf);
+
+    /* Left trim */
+    while (pj_isspace(*buf)) {
+	++buf;
+	--len;
+    }
+
+    /* Remove trailing newlines */
+    while (len && (buf[len-1] == '\r' || buf[len-1] == '\n'))
+	buf[--len] = '\0';
+
+    if (len == 0 || buf[0]=='q')
+	return;
+
+    if (pj_isdigit(*buf) || *buf=='-') {
+	
+	int i;
+	
+	if (*buf=='-')
+	    i = 1;
+	else
+	    i = 0;
+
+	for (; i<len; ++i) {
+	    if (!pj_isdigit(buf[i])) {
+		puts("Invalid input");
+		return;
+	    }
+	}
+
+	result->nb_result = my_atoi(buf);
+
+	if (result->nb_result >= 0 && 
+	    result->nb_result <= (int)pjsua_get_buddy_count()) 
+	{
+	    return;
+	}
+	if (result->nb_result == -1)
+	    return;
+
+	puts("Invalid input");
+	result->nb_result = NO_NB;
+	return;
+
+    } else {
+	pj_status_t status;
+
+	if ((status=pjsua_verify_url(buf)) != PJ_SUCCESS) {
+	    pjsua_perror(THIS_FILE, "Invalid URL", status);
+	    return;
+	}
+
+	result->uri_result = buf;
+    }
+}
+
+static pj_bool_t simple_input(const char *title, char *buf, pj_size_t len)
+{
+    char *p;
+
+    printf("%s (empty to cancel): ", title); fflush(stdout);
+    if (fgets(buf, len, stdin) == NULL)
+	return PJ_FALSE;
+
+    /* Remove trailing newlines. */
+    for (p=buf; ; ++p) {
+	if (*p=='\r' || *p=='\n') *p='\0';
+	else if (!*p) break;
+    }
+
+    if (!*buf)
+	return PJ_FALSE;
+    
+    return PJ_TRUE;
+}
+
+/*
+ * Print account status.
+ */
+static void print_acc_status(int acc_id)
+{
+    char buf[80];
+    pjsua_acc_info info;
+
+    pjsua_acc_get_info(acc_id, &info);
+
+    if (!info.has_registration) {
+	pj_ansi_snprintf(buf, sizeof(buf), "%.*s", 
+			 (int)info.status_text.slen,
+			 info.status_text.ptr);
+
+    } else {
+	pj_ansi_snprintf(buf, sizeof(buf),
+			 "%d/%.*s (expires=%d)",
+			 info.status,
+			 (int)info.status_text.slen,
+			 info.status_text.ptr,
+			 info.expires);
+
+    }
+
+    printf(" %c[%2d] %.*s: %s\n", (acc_id==current_acc?'*':' '),
+	   acc_id,  (int)info.acc_uri.slen, info.acc_uri.ptr, buf);
+    printf("       Online status: %.*s\n", 
+	(int)info.online_status_text.slen,
+	info.online_status_text.ptr);
+}
+
+/*
+ * Show a bit of help.
+ */
+static void keystroke_help()
+{
+    pjsua_acc_id acc_ids[16];
+    unsigned count = PJ_ARRAY_SIZE(acc_ids);
+    int i;
+
+    printf(">>>>\n");
+
+    pjsua_enum_accs(acc_ids, &count);
+
+    printf("Account list:\n");
+    for (i=0; i<(int)count; ++i)
+	print_acc_status(acc_ids[i]);
+
+    print_buddy_list();
+    
+    //puts("Commands:");
+    puts("+=============================================================================+");
+    puts("|       Call Commands:         |   Buddy, IM & Presence:  |     Account:      |");
+    puts("|                              |                          |                   |");
+    puts("|  m  Make new call            | +b  Add new buddy       .| +a  Add new accnt |");
+    puts("|  M  Make multiple calls      | -b  Delete buddy         | -a  Delete accnt. |");
+    puts("|  a  Answer call              |  i  Send IM              | !a  Modify accnt. |");
+    puts("|  h  Hangup call  (ha=all)    |  s  Subscribe presence   | rr  (Re-)register |");
+    puts("|  H  Hold call                |  u  Unsubscribe presence | ru  Unregister    |");
+    puts("|  v  re-inVite (release hold) |  t  ToGgle Online status |  >  Cycle next ac.|");
+    puts("|  U  send UPDATE              |  T  Set online status    |  <  Cycle prev ac.|");
+    puts("| ],[ Select next/prev call    +--------------------------+-------------------+");
+    puts("|  x  Xfer call                |      Media Commands:     |  Status & Config: |");
+    puts("|  X  Xfer with Replaces       |                          |                   |");
+    puts("|  #  Send RFC 2833 DTMF       | cl  List ports           |  d  Dump status   |");
+    puts("|  *  Send DTMF with INFO      | cc  Connect port         | dd  Dump detailed |");
+    puts("| dq  Dump curr. call quality  | cd  Disconnect port      | dc  Dump config   |");
+    puts("|                              |  V  Adjust audio Volume  |  f  Save config   |");
+    puts("|  S  Send arbitrary REQUEST   | Cp  Codec priorities     |                   |");
+    puts("+-----------------------------------------------------------------------------+");
+#if PJSUA_HAS_VIDEO
+    puts("| Video: \"vid help\" for more info                                             |");
+    puts("+-----------------------------------------------------------------------------+");
+#endif
+    puts("|  q  QUIT   L  ReLoad   sleep MS   echo [0|1|txt]     n: detect NAT type     |");
+    puts("+=============================================================================+");
+
+    i = pjsua_call_get_count();
+    printf("You have %d active call%s\n", i, (i>1?"s":""));
+
+    if (current_call != PJSUA_INVALID_ID) {
+	pjsua_call_info ci;
+	if (pjsua_call_get_info(current_call, &ci)==PJ_SUCCESS)
+	    printf("Current call id=%d to %.*s [%.*s]\n", current_call,
+		   (int)ci.remote_info.slen, ci.remote_info.ptr,
+		   (int)ci.state_text.slen, ci.state_text.ptr);
+    }
+}
+
+/* Help screen for video */
+#if PJSUA_HAS_VIDEO
+static void vid_show_help()
+{
+    pj_bool_t vid_enabled = (app_config.vid.vid_cnt > 0);
+
+    puts("+=============================================================================+");
+    puts("|                            Video commands:                                  |");
+    puts("|                                                                             |");
+    puts("| vid help                  Show this help screen                             |");
+    puts("| vid enable|disable        Enable or disable video in next offer/answer      |");
+    puts("| vid acc show              Show current account video settings               |");
+    puts("| vid acc autorx on|off     Automatically show incoming video on/off          |");
+    puts("| vid acc autotx on|off     Automatically offer video on/off                  |");
+    puts("| vid acc cap ID            Set default capture device for current acc        |");
+    puts("| vid acc rend ID           Set default renderer device for current acc       |");
+    puts("| vid call rx on|off N      Enable/disable video RX for stream N in curr call |");
+    puts("| vid call tx on|off N      Enable/disable video TX for stream N in curr call |");
+    puts("| vid call add              Add video stream for current call                 |");
+    puts("| vid call enable|disable N Enable/disable stream #N in current call          |");
+    puts("| vid call cap N ID         Set capture dev ID for stream #N in current call  |");
+    puts("| vid dev list              List all video devices                            |");
+    puts("| vid dev refresh           Refresh video device list                         |");
+    puts("| vid dev prev on|off ID    Enable/disable preview for specified device ID    |");
+    puts("| vid codec list            List video codecs                                 |");
+    puts("| vid codec prio ID PRIO    Set codec ID priority to PRIO                     |");
+    puts("| vid codec fps ID NUM DEN  Set codec ID framerate to (NUM/DEN) fps           |");
+    puts("| vid codec bw ID AVG MAX   Set codec ID bitrate to AVG & MAX kbps            |");
+    puts("| vid codec size ID W H     Set codec ID size/resolution to W x H             |");
+    puts("| vid win list              List all active video windows                     |");
+    puts("| vid win arrange           Auto arrange windows                              |");
+    puts("| vid win show|hide ID      Show/hide the specified video window ID           |");
+    puts("| vid win move ID X Y       Move window ID to position X,Y                    |");
+    puts("| vid win resize ID w h     Resize window ID to the specified width, height   |");
+    puts("+=============================================================================+");
+    printf("| Video will be %s in the next offer/answer %s                            |\n",
+	   (vid_enabled? "enabled" : "disabled"), (vid_enabled? " " : ""));
+    puts("+=============================================================================+");
+}
+
+static void vid_handle_menu(char *menuin)
+{
+    char *argv[8];
+    int argc = 0;
+
+    /* Tokenize */
+    argv[argc] = strtok(menuin, " \t\r\n");
+    while (argv[argc] && *argv[argc]) {
+	argc++;
+	argv[argc] = strtok(NULL, " \t\r\n");
+    }
+
+    if (argc == 1 || strcmp(argv[1], "help")==0) {
+	vid_show_help();
+    } else if (argc == 2 && (strcmp(argv[1], "enable")==0 ||
+			     strcmp(argv[1], "disable")==0))
+    {
+	pj_bool_t enabled = (strcmp(argv[1], "enable")==0);
+	app_config.vid.vid_cnt = (enabled ? 1 : 0);
+	PJ_LOG(3,(THIS_FILE, "Video will be %s in next offer/answer",
+		  (enabled?"enabled":"disabled")));
+    } else if (strcmp(argv[1], "acc")==0) {
+	pjsua_acc_config acc_cfg;
+	pj_bool_t changed = PJ_FALSE;
+
+	pjsua_acc_get_config(current_acc, &acc_cfg);
+
+	if (argc == 3 && strcmp(argv[2], "show")==0) {
+	    app_config_show_video(current_acc, &acc_cfg);
+	} else if (argc == 4 && strcmp(argv[2], "autorx")==0) {
+	    int on = (strcmp(argv[3], "on")==0);
+	    acc_cfg.vid_in_auto_show = on;
+	    changed = PJ_TRUE;
+	} else if (argc == 4 && strcmp(argv[2], "autotx")==0) {
+	    int on = (strcmp(argv[3], "on")==0);
+	    acc_cfg.vid_out_auto_transmit = on;
+	    changed = PJ_TRUE;
+	} else if (argc == 4 && strcmp(argv[2], "cap")==0) {
+	    int dev = atoi(argv[3]);
+	    acc_cfg.vid_cap_dev = dev;
+	    changed = PJ_TRUE;
+	} else if (argc == 4 && strcmp(argv[2], "rend")==0) {
+	    int dev = atoi(argv[3]);
+	    acc_cfg.vid_rend_dev = dev;
+	    changed = PJ_TRUE;
+	} else {
+	    goto on_error;
+	}
+
+	if (changed) {
+	    pj_status_t status = pjsua_acc_modify(current_acc, &acc_cfg);
+	    if (status != PJ_SUCCESS)
+		PJ_PERROR(1,(THIS_FILE, status, "Error modifying account %d",
+			     current_acc));
+	}
+
+    } else if (strcmp(argv[1], "call")==0) {
+	pjsua_call_vid_strm_op_param param;
+	pj_status_t status = PJ_SUCCESS;
+
+	pjsua_call_vid_strm_op_param_default(&param);
+
+	if (argc == 5 && strcmp(argv[2], "rx")==0) {
+	    pjsua_stream_info si;
+	    pj_bool_t on = (strcmp(argv[3], "on") == 0);
+
+	    param.med_idx = atoi(argv[4]);
+	    if (pjsua_call_get_stream_info(current_call, param.med_idx, &si) ||
+		si.type != PJMEDIA_TYPE_VIDEO)
+	    {
+		PJ_PERROR(1,(THIS_FILE, PJ_EINVAL, "Invalid stream"));
+		return;
+	    }
+
+	    if (on) param.dir = (si.info.vid.dir | PJMEDIA_DIR_DECODING);
+	    else param.dir = (si.info.vid.dir & PJMEDIA_DIR_ENCODING);
+
+	    status = pjsua_call_set_vid_strm(current_call,
+	                                     PJSUA_CALL_VID_STRM_CHANGE_DIR,
+	                                     &param);
+	}
+	else if (argc == 5 && strcmp(argv[2], "tx")==0) {
+	    pj_bool_t on = (strcmp(argv[3], "on") == 0);
+	    pjsua_call_vid_strm_op op = on? PJSUA_CALL_VID_STRM_START_TRANSMIT :
+					    PJSUA_CALL_VID_STRM_STOP_TRANSMIT;
+
+	    param.med_idx = atoi(argv[4]);
+
+	    status = pjsua_call_set_vid_strm(current_call, op, &param);
+	}
+	else if (argc == 3 && strcmp(argv[2], "add")==0) {
+	    status = pjsua_call_set_vid_strm(current_call,
+	                                     PJSUA_CALL_VID_STRM_ADD, NULL);
+	}
+	else if (argc >= 3 && 
+		 (strcmp(argv[2], "disable")==0 || strcmp(argv[2], "enable")==0))
+	{
+	    pj_bool_t enable = (strcmp(argv[2], "enable") == 0);
+	    pjsua_call_vid_strm_op op = enable? PJSUA_CALL_VID_STRM_CHANGE_DIR :
+						PJSUA_CALL_VID_STRM_REMOVE;
+
+	    param.med_idx = argc >= 4? atoi(argv[3]) : -1;
+	    param.dir = PJMEDIA_DIR_ENCODING_DECODING;
+	    status = pjsua_call_set_vid_strm(current_call, op, &param);
+	}
+	else if (argc >= 3 && strcmp(argv[2], "cap")==0) {
+	    param.med_idx = argc >= 4? atoi(argv[3]) : -1;
+	    param.cap_dev = argc >= 5? atoi(argv[4]) : PJMEDIA_VID_DEFAULT_CAPTURE_DEV;
+	    status = pjsua_call_set_vid_strm(current_call,
+	                                     PJSUA_CALL_VID_STRM_CHANGE_CAP_DEV,
+	                                     &param);
+	} else
+	    goto on_error;
+
+	if (status != PJ_SUCCESS) {
+	    PJ_PERROR(1,(THIS_FILE, status, "Error modifying video stream"));
+	}
+
+    } else if (argc >= 3 && strcmp(argv[1], "dev")==0) {
+	if (strcmp(argv[2], "list")==0) {
+	    vid_list_devs();
+	} else if (strcmp(argv[2], "refresh")==0) {
+	    pjmedia_vid_dev_refresh();
+	} else if (strcmp(argv[2], "prev")==0) {
+	    if (argc != 5) {
+		goto on_error;
+	    } else {
+		pj_bool_t on = (strcmp(argv[3], "on") == 0);
+		int dev_id = atoi(argv[4]);
+		if (on) {
+                    pjsua_vid_preview_param param;
+
+                    pjsua_vid_preview_param_default(&param);
+                    param.wnd_flags = PJMEDIA_VID_DEV_WND_BORDER |
+                                      PJMEDIA_VID_DEV_WND_RESIZABLE;
+		    pjsua_vid_preview_start(dev_id, &param);
+		    arrange_window(pjsua_vid_preview_get_win(dev_id));
+		} else {
+		    pjsua_vid_win_id wid;
+		    wid = pjsua_vid_preview_get_win(dev_id);
+		    if (wid != PJSUA_INVALID_ID) {
+			/* Preview window hiding once it is stopped is
+			 * responsibility of app */
+			pjsua_vid_win_set_show(wid, PJ_FALSE);
+			pjsua_vid_preview_stop(dev_id);
+		    }
+		}
+	    }
+	} else
+	    goto on_error;
+    } else if (strcmp(argv[1], "win")==0) {
+	pj_status_t status = PJ_SUCCESS;
+
+	if (argc==3 && strcmp(argv[2], "list")==0) {
+	    pjsua_vid_win_id wids[PJSUA_MAX_VID_WINS];
+	    unsigned i, cnt = PJ_ARRAY_SIZE(wids);
+
+	    pjsua_vid_enum_wins(wids, &cnt);
+
+	    PJ_LOG(3,(THIS_FILE, "Found %d video windows:", cnt));
+	    PJ_LOG(3,(THIS_FILE, "WID show    pos       size"));
+	    PJ_LOG(3,(THIS_FILE, "------------------------------"));
+	    for (i = 0; i < cnt; ++i) {
+		pjsua_vid_win_info wi;
+		pjsua_vid_win_get_info(wids[i], &wi);
+		PJ_LOG(3,(THIS_FILE, "%3d   %c  (%d,%d)  %dx%d",
+			  wids[i], (wi.show?'Y':'N'), wi.pos.x, wi.pos.y,
+			  wi.size.w, wi.size.h));
+	    }
+	} else if (argc==4 && (strcmp(argv[2], "show")==0 ||
+			       strcmp(argv[2], "hide")==0))
+	{
+	    pj_bool_t show = (strcmp(argv[2], "show")==0);
+	    pjsua_vid_win_id wid = atoi(argv[3]);
+	    status = pjsua_vid_win_set_show(wid, show);
+	} else if (argc==6 && strcmp(argv[2], "move")==0) {
+	    pjsua_vid_win_id wid = atoi(argv[3]);
+	    pjmedia_coord pos;
+
+	    pos.x = atoi(argv[4]);
+	    pos.y = atoi(argv[5]);
+	    status = pjsua_vid_win_set_pos(wid, &pos);
+	} else if (argc==6 && strcmp(argv[2], "resize")==0) {
+	    pjsua_vid_win_id wid = atoi(argv[3]);
+	    pjmedia_rect_size size;
+
+	    size.w = atoi(argv[4]);
+	    size.h = atoi(argv[5]);
+	    status = pjsua_vid_win_set_size(wid, &size);
+	} else if (argc==3 && strcmp(argv[2], "arrange")==0) {
+	    arrange_window(PJSUA_INVALID_ID);
+	} else
+	    goto on_error;
+
+	if (status != PJ_SUCCESS) {
+	    PJ_PERROR(1,(THIS_FILE, status, "Window operation error"));
+	}
+
+    } else if (strcmp(argv[1], "codec")==0) {
+	pjsua_codec_info ci[PJMEDIA_CODEC_MGR_MAX_CODECS];
+	unsigned count = PJ_ARRAY_SIZE(ci);
+	pj_status_t status;
+
+	if (argc==3 && strcmp(argv[2], "list")==0) {
+	    status = pjsua_vid_enum_codecs(ci, &count);
+	    if (status != PJ_SUCCESS) {
+		PJ_PERROR(1,(THIS_FILE, status, "Error enumerating codecs"));
+	    } else {
+		unsigned i;
+		PJ_LOG(3,(THIS_FILE, "Found %d video codecs:", count));
+		PJ_LOG(3,(THIS_FILE, "codec id      prio  fps    bw(kbps)   size"));
+		PJ_LOG(3,(THIS_FILE, "------------------------------------------"));
+		for (i=0; i<count; ++i) {
+		    pjmedia_vid_codec_param cp;
+		    pjmedia_video_format_detail *vfd;
+
+		    status = pjsua_vid_codec_get_param(&ci[i].codec_id, &cp);
+		    if (status != PJ_SUCCESS)
+			continue;
+
+		    vfd = pjmedia_format_get_video_format_detail(&cp.enc_fmt,
+								 PJ_TRUE);
+		    PJ_LOG(3,(THIS_FILE, "%.*s%.*s %3d %7.2f  %4d/%4d  %dx%d", 
+			      (int)ci[i].codec_id.slen, ci[i].codec_id.ptr,
+			      13-(int)ci[i].codec_id.slen, "                ",
+			      ci[i].priority,
+			      (vfd->fps.num*1.0/vfd->fps.denum),
+			      vfd->avg_bps/1000, vfd->max_bps/1000,
+			      vfd->size.w, vfd->size.h));
+		}
+	    }
+	} else if (argc==5 && strcmp(argv[2], "prio")==0) {
+	    pj_str_t cid;
+	    int prio;
+	    cid = pj_str(argv[3]);
+	    prio = atoi(argv[4]);
+	    status = pjsua_vid_codec_set_priority(&cid, (pj_uint8_t)prio);
+	    if (status != PJ_SUCCESS)
+		PJ_PERROR(1,(THIS_FILE, status, "Set codec priority error"));
+	} else if (argc==6 && strcmp(argv[2], "fps")==0) {
+	    pjmedia_vid_codec_param cp;
+	    pj_str_t cid;
+	    int M, N;
+	    cid = pj_str(argv[3]);
+	    M = atoi(argv[4]);
+	    N = atoi(argv[5]);
+	    status = pjsua_vid_codec_get_param(&cid, &cp);
+	    if (status == PJ_SUCCESS) {
+		cp.enc_fmt.det.vid.fps.num = M;
+		cp.enc_fmt.det.vid.fps.denum = N;
+		status = pjsua_vid_codec_set_param(&cid, &cp);
+	    }
+	    if (status != PJ_SUCCESS)
+		PJ_PERROR(1,(THIS_FILE, status, "Set codec framerate error"));
+	} else if (argc==6 && strcmp(argv[2], "bw")==0) {
+	    pjmedia_vid_codec_param cp;
+	    pj_str_t cid;
+	    int M, N;
+	    cid = pj_str(argv[3]);
+	    M = atoi(argv[4]);
+	    N = atoi(argv[5]);
+	    status = pjsua_vid_codec_get_param(&cid, &cp);
+	    if (status == PJ_SUCCESS) {
+		cp.enc_fmt.det.vid.avg_bps = M * 1000;
+		cp.enc_fmt.det.vid.max_bps = N * 1000;
+		status = pjsua_vid_codec_set_param(&cid, &cp);
+	    }
+	    if (status != PJ_SUCCESS)
+		PJ_PERROR(1,(THIS_FILE, status, "Set codec bitrate error"));
+	} else if (argc==6 && strcmp(argv[2], "size")==0) {
+	    pjmedia_vid_codec_param cp;
+	    pj_str_t cid;
+	    int M, N;
+	    cid = pj_str(argv[3]);
+	    M = atoi(argv[4]);
+	    N = atoi(argv[5]);
+	    status = pjsua_vid_codec_get_param(&cid, &cp);
+	    if (status == PJ_SUCCESS) {
+		cp.enc_fmt.det.vid.size.w = M;
+		cp.enc_fmt.det.vid.size.h = N;
+		status = pjsua_vid_codec_set_param(&cid, &cp);
+	    }
+	    if (status != PJ_SUCCESS)
+		PJ_PERROR(1,(THIS_FILE, status, "Set codec size error"));
+	} else
+	    goto on_error;
+    } else
+	goto on_error;
+
+    return;
+
+on_error:
+    PJ_LOG(1,(THIS_FILE, "Invalid command, use 'vid help'"));
+}
+
+#endif /* PJSUA_HAS_VIDEO */
+
+/** UI Command **/
+static void ui_make_new_call()
+{    
+    char buf[128];
+    pjsua_msg_data msg_data;
+    input_result result;
+    pj_str_t tmp;
+
+    printf("(You currently have %d calls)\n", pjsua_call_get_count());
+    
+    ui_input_url("Make call", buf, sizeof(buf), &result);
+    if (result.nb_result != NO_NB) {
+
+	if (result.nb_result == -1 || result.nb_result == 0) {
+	    puts("You can't do that with make call!");
+	    return;
+	} else {
+	    pjsua_buddy_info binfo;
+	    pjsua_buddy_get_info(result.nb_result-1, &binfo);
+	    tmp.ptr = buf;
+	    pj_strncpy(&tmp, &binfo.uri, sizeof(buf));
+	}
+
+    } else if (result.uri_result) {
+	tmp = pj_str(result.uri_result);
+    } else {
+	tmp.slen = 0;
+    }
+
+    pjsua_msg_data_init(&msg_data);
+    TEST_MULTIPART(&msg_data);
+    pjsua_call_make_call(current_acc, &tmp, &call_opt, NULL, 
+			 &msg_data, &current_call);
+}
+
+static void ui_make_multi_call()
+{
+    char menuin[32];
+    int count;
+    char buf[128];
+    input_result result;
+    pj_str_t tmp;
+    int i;
+
+    printf("(You currently have %d calls)\n", pjsua_call_get_count());
+
+    if (!simple_input("Number of calls", menuin, sizeof(menuin)))
+	return;
+
+    count = my_atoi(menuin);
+    if (count < 1)
+	return;
+
+    ui_input_url("Make call", buf, sizeof(buf), &result);
+    if (result.nb_result != NO_NB) {
+	pjsua_buddy_info binfo;
+	if (result.nb_result == -1 || result.nb_result == 0) {
+	    puts("You can't do that with make call!");
+	    return;
+	}
+	pjsua_buddy_get_info(result.nb_result-1, &binfo);
+	tmp.ptr = buf;
+	pj_strncpy(&tmp, &binfo.uri, sizeof(buf));
+    } else {
+	tmp = pj_str(result.uri_result);
+    }
+
+    for (i=0; i<my_atoi(menuin); ++i) {
+	pj_status_t status;
+
+	status = pjsua_call_make_call(current_acc, &tmp, &call_opt, NULL,
+	    NULL, NULL);
+	if (status != PJ_SUCCESS)
+	    break;
+    }
+}
+
+static void ui_detect_nat_type()
+{
+    int i = pjsua_detect_nat_type();
+    if (i != PJ_SUCCESS)
+	pjsua_perror(THIS_FILE, "Error", i);
+}
+
+static void ui_send_instant_message()
+{
+    char *uri = NULL;
+    /* i is for call index to send message, if any */
+    int i = -1;
+    input_result result;
+    char buf[128];
+    char text[128];
+    pj_str_t tmp;
+
+    /* Input destination. */
+    ui_input_url("Send IM to", buf, sizeof(buf), &result);
+    if (result.nb_result != NO_NB) {
+
+	if (result.nb_result == -1) {
+	    puts("You can't send broadcast IM like that!");
+	    return;
+
+	} else if (result.nb_result == 0) {
+	    i = current_call;
+	} else {
+	    pjsua_buddy_info binfo;
+	    pjsua_buddy_get_info(result.nb_result-1, &binfo);
+	    tmp.ptr = buf;
+	    pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(buf));
+	    uri = buf;
+	}
+
+    } else if (result.uri_result) {
+	uri = result.uri_result;
+    }
+
+
+    /* Send typing indication. */
+    if (i != -1)
+	pjsua_call_send_typing_ind(i, PJ_TRUE, NULL);
+    else {
+	pj_str_t tmp_uri = pj_str(uri);
+	pjsua_im_typing(current_acc, &tmp_uri, PJ_TRUE, NULL);
+    }
+
+    /* Input the IM . */
+    if (!simple_input("Message", text, sizeof(text))) {
+	/*
+	* Cancelled.
+	* Send typing notification too, saying we're not typing.
+	*/
+	if (i != -1)
+	    pjsua_call_send_typing_ind(i, PJ_FALSE, NULL);
+	else {
+	    pj_str_t tmp_uri = pj_str(uri);
+	    pjsua_im_typing(current_acc, &tmp_uri, PJ_FALSE, NULL);
+	}
+	return;
+    }
+
+    tmp = pj_str(text);
+
+    /* Send the IM */
+    if (i != -1)
+	pjsua_call_send_im(i, NULL, &tmp, NULL, NULL);
+    else {
+	pj_str_t tmp_uri = pj_str(uri);
+	pjsua_im_send(current_acc, &tmp_uri, NULL, &tmp, NULL, NULL);
+    }
+}
+
+static void ui_answer_call()
+{
+    pjsua_call_info call_info;
+    char buf[128];
+    pjsua_msg_data msg_data;
+
+    if (current_call != -1) {
+	pjsua_call_get_info(current_call, &call_info);
+    } else {
+	/* Make compiler happy */
+	call_info.role = PJSIP_ROLE_UAC;
+	call_info.state = PJSIP_INV_STATE_DISCONNECTED;
+    }
+
+    if (current_call == -1 || 
+	call_info.role != PJSIP_ROLE_UAS ||
+	call_info.state >= PJSIP_INV_STATE_CONNECTING)
+    {
+	puts("No pending incoming call");
+	fflush(stdout);
+	return;
+
+    } else {
+	int st_code;
+	char contact[120];
+	pj_str_t hname = { "Contact", 7 };
+	pj_str_t hvalue;
+	pjsip_generic_string_hdr hcontact;
+
+	if (!simple_input("Answer with code (100-699)", buf, sizeof(buf)))
+	    return;
+
+	st_code = my_atoi(buf);
+	if (st_code < 100)
+	    return;
+
+	pjsua_msg_data_init(&msg_data);
+
+	if (st_code/100 == 3) {
+	    if (!simple_input("Enter URL to be put in Contact", 
+		contact, sizeof(contact)))
+		return;
+	    hvalue = pj_str(contact);
+	    pjsip_generic_string_hdr_init2(&hcontact, &hname, &hvalue);
+
+	    pj_list_push_back(&msg_data.hdr_list, &hcontact);
+	}
+
+	/*
+	* Must check again!
+	* Call may have been disconnected while we're waiting for 
+	* keyboard input.
+	*/
+	if (current_call == -1) {
+	    puts("Call has been disconnected");
+	    fflush(stdout);
+	    return;
+	}
+
+	pjsua_call_answer2(current_call, &call_opt, st_code, NULL, &msg_data);
+    }    
+}
+
+static void ui_hangup_call(char menuin[])
+{
+    if (current_call == -1) {
+	puts("No current call");
+	fflush(stdout);
+	return;
+
+    } else if (menuin[1] == 'a') {
+	/* Hangup all calls */
+	pjsua_call_hangup_all();
+    } else {
+	/* Hangup current calls */
+	pjsua_call_hangup(current_call, 0, NULL, NULL);
+    }
+}
+
+static void ui_cycle_dialog(char menuin[])
+{
+    if (menuin[0] == ']') {
+	find_next_call();
+
+    } else {
+	find_prev_call();
+    }
+
+    if (current_call != -1) {
+	pjsua_call_info call_info;
+
+	pjsua_call_get_info(current_call, &call_info);
+	PJ_LOG(3,(THIS_FILE,"Current dialog: %.*s", 
+	    (int)call_info.remote_info.slen, 
+	    call_info.remote_info.ptr));
+
+    } else {
+	PJ_LOG(3,(THIS_FILE,"No current dialog"));
+    }
+}
+
+static void ui_cycle_account()
+{
+    int i;
+    char buf[128];
+
+    if (!simple_input("Enter account ID to select", buf, sizeof(buf)))
+	return;
+
+    i = my_atoi(buf);
+    if (pjsua_acc_is_valid(i)) {
+	pjsua_acc_set_default(i);
+	PJ_LOG(3,(THIS_FILE, "Current account changed to %d", i));
+    } else {
+	PJ_LOG(3,(THIS_FILE, "Invalid account id %d", i));
+    }
+}
+
+static void ui_add_buddy()
+{
+    char buf[128];
+    pjsua_buddy_config buddy_cfg;
+    pjsua_buddy_id buddy_id;
+    pj_status_t status;
+
+    if (!simple_input("Enter buddy's URI:", buf, sizeof(buf)))
+	return;
+
+    if (pjsua_verify_url(buf) != PJ_SUCCESS) {
+	printf("Invalid URI '%s'\n", buf);
+	return;
+    }
+
+    pj_bzero(&buddy_cfg, sizeof(pjsua_buddy_config));
+
+    buddy_cfg.uri = pj_str(buf);
+    buddy_cfg.subscribe = PJ_TRUE;
+
+    status = pjsua_buddy_add(&buddy_cfg, &buddy_id);
+    if (status == PJ_SUCCESS) {
+	printf("New buddy '%s' added at index %d\n",
+	    buf, buddy_id+1);
+    }
+}
+
+static void ui_add_account(pjsua_transport_config *rtp_cfg)
+{
+    char id[80], registrar[80], realm[80], uname[80], passwd[30];
+    pjsua_acc_config acc_cfg;
+    pj_status_t status;
+
+    if (!simple_input("Your SIP URL:", id, sizeof(id)))
+	return;
+    if (!simple_input("URL of the registrar:", registrar, sizeof(registrar)))
+	return;
+    if (!simple_input("Auth Realm:", realm, sizeof(realm)))
+	return;
+    if (!simple_input("Auth Username:", uname, sizeof(uname)))
+	return;
+    if (!simple_input("Auth Password:", passwd, sizeof(passwd)))
+	return;
+
+    pjsua_acc_config_default(&acc_cfg);
+    acc_cfg.id = pj_str(id);
+    acc_cfg.reg_uri = pj_str(registrar);
+    acc_cfg.cred_count = 1;
+    acc_cfg.cred_info[0].scheme = pj_str("Digest");
+    acc_cfg.cred_info[0].realm = pj_str(realm);
+    acc_cfg.cred_info[0].username = pj_str(uname);
+    acc_cfg.cred_info[0].data_type = 0;
+    acc_cfg.cred_info[0].data = pj_str(passwd);
+
+    acc_cfg.rtp_cfg = *rtp_cfg;    
+    app_config_init_video(&acc_cfg);
+
+    status = pjsua_acc_add(&acc_cfg, PJ_TRUE, NULL);
+    if (status != PJ_SUCCESS) {
+	pjsua_perror(THIS_FILE, "Error adding new account", status);
+    }
+}
+
+static void ui_delete_buddy()
+{
+    char buf[128];
+    int i;
+
+    if (!simple_input("Enter buddy ID to delete", buf, sizeof(buf)))
+	return;
+
+    i = my_atoi(buf) - 1;
+
+    if (!pjsua_buddy_is_valid(i)) {
+	printf("Invalid buddy id %d\n", i);
+    } else {
+	pjsua_buddy_del(i);
+	printf("Buddy %d deleted\n", i);
+    }
+}
+
+static void ui_delete_account()
+{
+    char buf[128];
+    int i;
+
+    if (!simple_input("Enter account ID to delete", buf, sizeof(buf)))
+	return;
+
+    i = my_atoi(buf);
+
+    if (!pjsua_acc_is_valid(i)) {
+	printf("Invalid account id %d\n", i);
+    } else {
+	pjsua_acc_del(i);
+	printf("Account %d deleted\n", i);
+    }
+}
+
+static void ui_call_hold()
+{
+    if (current_call != -1) {		
+	pjsua_call_set_hold(current_call, NULL);
+    } else {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    }
+}
+
+static void ui_call_reinvite()
+{
+    call_opt.flag |= PJSUA_CALL_UNHOLD;
+    pjsua_call_reinvite2(current_call, &call_opt, NULL);
+}
+
+static void ui_send_update()
+{
+    if (current_call != -1) {		
+	pjsua_call_update2(current_call, &call_opt, NULL);
+    } else {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    }
+}
+
+/*
+ * Change codec priorities.
+ */
+static void ui_manage_codec_prio()
+{
+    pjsua_codec_info c[32];
+    unsigned i, count = PJ_ARRAY_SIZE(c);
+    char input[32];
+    char *codec, *prio;
+    pj_str_t id;
+    int new_prio;
+    pj_status_t status;
+
+    printf("List of audio codecs:\n");
+    pjsua_enum_codecs(c, &count);
+    for (i=0; i<count; ++i) {
+	printf("  %d\t%.*s\n", c[i].priority, (int)c[i].codec_id.slen,
+			       c[i].codec_id.ptr);
+    }
+
+#if PJSUA_HAS_VIDEO
+    puts("");
+    printf("List of video codecs:\n");
+    pjsua_vid_enum_codecs(c, &count);
+    for (i=0; i<count; ++i) {
+	printf("  %d\t%.*s%s%.*s\n", c[i].priority,
+				     (int)c[i].codec_id.slen,
+				     c[i].codec_id.ptr,
+				     c[i].desc.slen? " - ":"",
+				     (int)c[i].desc.slen,
+				     c[i].desc.ptr);
+    }
+#endif
+
+    puts("");
+    puts("Enter codec id and its new priority (e.g. \"speex/16000 200\", "
+	 """\"H263 200\"),");
+    puts("or empty to cancel.");
+
+    printf("Codec name (\"*\" for all) and priority: ");
+    if (fgets(input, sizeof(input), stdin) == NULL)
+	return;
+    if (input[0]=='\r' || input[0]=='\n') {
+	puts("Done");
+	return;
+    }
+
+    codec = strtok(input, " \t\r\n");
+    prio = strtok(NULL, " \r\n");
+
+    if (!codec || !prio) {
+	puts("Invalid input");
+	return;
+    }
+
+    new_prio = atoi(prio);
+    if (new_prio < 0) 
+	new_prio = 0;
+    else if (new_prio > PJMEDIA_CODEC_PRIO_HIGHEST) 
+	new_prio = PJMEDIA_CODEC_PRIO_HIGHEST;
+
+    status = pjsua_codec_set_priority(pj_cstr(&id, codec), 
+				      (pj_uint8_t)new_prio);
+#if PJSUA_HAS_VIDEO
+    if (status != PJ_SUCCESS) {
+	status = pjsua_vid_codec_set_priority(pj_cstr(&id, codec), 
+					      (pj_uint8_t)new_prio);
+    }
+#endif
+    if (status != PJ_SUCCESS)
+	pjsua_perror(THIS_FILE, "Error setting codec priority", status);
+}
+
+static void ui_call_transfer(pj_bool_t no_refersub)
+{
+    if (current_call == -1) {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    } else {
+	int call = current_call;
+	char buf[128];
+	pjsip_generic_string_hdr refer_sub;
+	pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 };
+	pj_str_t STR_FALSE = { "false", 5 };
+	pjsua_call_info ci;
+	input_result result;
+	pjsua_msg_data msg_data;
+
+	pjsua_call_get_info(current_call, &ci);
+	printf("Transfering current call [%d] %.*s\n", current_call,
+	       (int)ci.remote_info.slen, ci.remote_info.ptr);
+
+	ui_input_url("Transfer to URL", buf, sizeof(buf), &result);
+
+	/* Check if call is still there. */
+
+	if (call != current_call) {
+	    puts("Call has been disconnected");
+	    return;
+	}
+
+	pjsua_msg_data_init(&msg_data);
+	if (no_refersub) {
+	    /* Add Refer-Sub: false in outgoing REFER request */
+	    pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB,
+		&STR_FALSE);
+	    pj_list_push_back(&msg_data.hdr_list, &refer_sub);
+	}
+	if (result.nb_result != NO_NB) {
+	    if (result.nb_result == -1 || result.nb_result == 0)
+		puts("You can't do that with transfer call!");
+	    else {
+		pjsua_buddy_info binfo;
+		pjsua_buddy_get_info(result.nb_result-1, &binfo);
+		pjsua_call_xfer( current_call, &binfo.uri, &msg_data);
+	    }
+
+	} else if (result.uri_result) {
+	    pj_str_t tmp;
+	    tmp = pj_str(result.uri_result);
+	    pjsua_call_xfer( current_call, &tmp, &msg_data);
+	}
+    }
+}
+
+static void ui_call_transfer_replaces(pj_bool_t no_refersub)
+{        
+    if (current_call == -1) {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    } else {
+	int call = current_call;
+	int dst_call;
+	pjsip_generic_string_hdr refer_sub;
+	pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 };
+	pj_str_t STR_FALSE = { "false", 5 };
+	pjsua_call_id ids[PJSUA_MAX_CALLS];
+	pjsua_call_info ci;
+	pjsua_msg_data msg_data;
+	char buf[128];
+	unsigned i, count;
+
+	count = PJ_ARRAY_SIZE(ids);
+	pjsua_enum_calls(ids, &count);
+
+	if (count <= 1) {
+	    puts("There are no other calls");
+	    return;
+	}
+
+	pjsua_call_get_info(current_call, &ci);
+	printf("Transfer call [%d] %.*s to one of the following:\n",
+	       current_call,
+	       (int)ci.remote_info.slen, ci.remote_info.ptr);
+
+	for (i=0; i<count; ++i) {
+	    pjsua_call_info call_info;
+
+	    if (ids[i] == call)
+		return;
+
+	    pjsua_call_get_info(ids[i], &call_info);
+	    printf("%d  %.*s [%.*s]\n",
+		ids[i],
+		(int)call_info.remote_info.slen,
+		call_info.remote_info.ptr,
+		(int)call_info.state_text.slen,
+		call_info.state_text.ptr);
+	}
+
+	if (!simple_input("Enter call number to be replaced", buf, sizeof(buf)))
+	    return;
+
+	dst_call = my_atoi(buf);
+
+	/* Check if call is still there. */
+
+	if (call != current_call) {
+	    puts("Call has been disconnected");
+	    return;
+	}
+
+	/* Check that destination call is valid. */
+	if (dst_call == call) {
+	    puts("Destination call number must not be the same "
+		"as the call being transfered");
+	    return;
+	}
+	if (dst_call >= PJSUA_MAX_CALLS) {
+	    puts("Invalid destination call number");
+	    return;
+	}
+	if (!pjsua_call_is_active(dst_call)) {
+	    puts("Invalid destination call number");
+	    return;
+	}
+
+	pjsua_msg_data_init(&msg_data);
+	if (no_refersub) {
+	    /* Add Refer-Sub: false in outgoing REFER request */
+	    pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, 
+					   &STR_FALSE);
+	    pj_list_push_back(&msg_data.hdr_list, &refer_sub);
+	}
+
+	pjsua_call_xfer_replaces(call, dst_call, 
+				 PJSUA_XFER_NO_REQUIRE_REPLACES, 
+				 &msg_data);
+    }
+}
+
+static void ui_send_dtmf_2833()
+{
+    if (current_call == -1) {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    } else if (!pjsua_call_has_media(current_call)) {
+	PJ_LOG(3,(THIS_FILE, "Media is not established yet!"));
+    } else {
+	pj_str_t digits;
+	int call = current_call;
+	pj_status_t status;
+	char buf[128];
+
+	if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, 
+	    sizeof(buf)))
+	{
+	    return;
+	}
+
+	if (call != current_call) {
+	    puts("Call has been disconnected");
+	    return;
+	}
+
+	digits = pj_str(buf);
+	status = pjsua_call_dial_dtmf(current_call, &digits);
+	if (status != PJ_SUCCESS) {
+	    pjsua_perror(THIS_FILE, "Unable to send DTMF", status);
+	} else {
+	    puts("DTMF digits enqueued for transmission");
+	}
+    }
+}
+
+static void ui_send_dtmf_info()
+{
+    if (current_call == -1) {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    } else {
+	const pj_str_t SIP_INFO = pj_str("INFO");
+	pj_str_t digits;
+	int call = current_call;
+	int i;
+	pj_status_t status;
+	char buf[128];
+
+	if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, 
+	    sizeof(buf)))
+	{
+	    return;
+	}
+
+	if (call != current_call) {
+	    puts("Call has been disconnected");
+	    return;
+	}
+
+	digits = pj_str(buf);
+	for (i=0; i<digits.slen; ++i) {
+	    char body[80];
+	    pjsua_msg_data msg_data;
+
+	    pjsua_msg_data_init(&msg_data);
+	    msg_data.content_type = pj_str("application/dtmf-relay");
+
+	    pj_ansi_snprintf(body, sizeof(body),
+		"Signal=%c\r\n"
+		"Duration=160",
+		buf[i]);
+	    msg_data.msg_body = pj_str(body);
+
+	    status = pjsua_call_send_request(current_call, &SIP_INFO, 
+		&msg_data);
+	    if (status != PJ_SUCCESS) {
+		return;
+	    }
+	}
+    }
+}
+
+static void ui_send_arbitrary_request()
+{
+    char text[128];
+    char buf[128];
+    char *uri;
+    input_result result;
+    pj_str_t tmp;
+
+    if (pjsua_acc_get_count() == 0) {
+	puts("Sorry, need at least one account configured");
+	return;
+    }
+
+    puts("Send arbitrary request to remote host");
+
+    /* Input METHOD */
+    if (!simple_input("Request method:",text,sizeof(text)))
+	return;
+
+    /* Input destination URI */
+    uri = NULL;
+    ui_input_url("Destination URI", buf, sizeof(buf), &result);
+    if (result.nb_result != NO_NB) {
+
+	if (result.nb_result == -1) {
+	    puts("Sorry you can't do that!");
+	    return;
+	} else if (result.nb_result == 0) {
+	    uri = NULL;
+	    if (current_call == PJSUA_INVALID_ID) {
+		puts("No current call");
+		return;
+	    }
+	} else {	    
+	    pjsua_buddy_info binfo;
+	    pjsua_buddy_get_info(result.nb_result-1, &binfo);
+	    tmp.ptr = buf;
+	    pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(buf));
+	    uri = buf;
+	}
+
+    } else if (result.uri_result) {
+	uri = result.uri_result;
+    } else {
+	return;
+    }
+
+    if (uri) {
+	tmp = pj_str(uri);
+	send_request(text, &tmp);
+    } else {
+	/* If you send call control request using this method
+	* (such requests includes BYE, CANCEL, etc.), it will
+	* not go well with the call state, so don't do it
+	* unless it's for testing.
+	*/
+	pj_str_t method = pj_str(text);
+	pjsua_call_send_request(current_call, &method, NULL);
+    }	    
+}
+
+static void ui_echo(char menuin[])
+{
+    if (pj_ansi_strnicmp(menuin, "echo", 4)==0) {
+	pj_str_t tmp;
+
+	tmp.ptr = menuin+5;
+	tmp.slen = pj_ansi_strlen(menuin)-6;
+
+	if (tmp.slen < 1) {
+	    puts("Usage: echo [0|1]");
+	    return;
+	}
+	cmd_echo = *tmp.ptr != '0' || tmp.slen!=1;
+    }
+}
+
+static void ui_sleep(char menuin[])
+{
+    if (pj_ansi_strnicmp(menuin, "sleep", 5)==0) {
+	pj_str_t tmp;
+	int delay;
+
+	tmp.ptr = menuin+6;
+	tmp.slen = pj_ansi_strlen(menuin)-7;
+
+	if (tmp.slen < 1) {
+	    puts("Usage: sleep MSEC");
+	    return;
+	}
+
+	delay = pj_strtoul(&tmp);
+	if (delay < 0) delay = 0;
+	pj_thread_sleep(delay);		
+    }
+}
+
+static void ui_subscribe(char menuin[])
+{
+    char buf[128];
+    input_result result;
+
+    ui_input_url("(un)Subscribe presence of", buf, sizeof(buf), &result);
+    if (result.nb_result != NO_NB) {
+	if (result.nb_result == -1) {
+	    int i, count;
+	    count = pjsua_get_buddy_count();
+	    for (i=0; i<count; ++i)
+		pjsua_buddy_subscribe_pres(i, menuin[0]=='s');
+	} else if (result.nb_result == 0) {
+	    puts("Sorry, can only subscribe to buddy's presence, "
+		"not from existing call");
+	} else {
+	    pjsua_buddy_subscribe_pres(result.nb_result-1, (menuin[0]=='s'));
+	}
+
+    } else if (result.uri_result) {
+	puts("Sorry, can only subscribe to buddy's presence, "
+	    "not arbitrary URL (for now)");
+    }
+}
+
+static void ui_register(char menuin[])
+{
+    switch (menuin[1]) {
+    case 'r':
+	/*
+	* Re-Register.
+	*/
+	pjsua_acc_set_registration(current_acc, PJ_TRUE);
+	break;
+    case 'u':
+	/*
+	* Unregister
+	*/
+	pjsua_acc_set_registration(current_acc, PJ_FALSE);
+	break;
+    }
+}
+
+static void ui_toggle_state()
+{
+    pjsua_acc_info acc_info;
+
+    pjsua_acc_get_info(current_acc, &acc_info);
+    acc_info.online_status = !acc_info.online_status;
+    pjsua_acc_set_online_status(current_acc, acc_info.online_status);
+    printf("Setting %s online status to %s\n",
+	   acc_info.acc_uri.ptr,
+	   (acc_info.online_status?"online":"offline"));
+}
+
+/*
+ * Change extended online status.
+ */
+static void ui_change_online_status()
+{
+    char menuin[32];
+    pj_bool_t online_status;
+    pjrpid_element elem;
+    int i, choice;
+
+    enum {
+	AVAILABLE, BUSY, OTP, IDLE, AWAY, BRB, OFFLINE, OPT_MAX
+    };
+
+    struct opt {
+	int id;
+	char *name;
+    } opts[] = {
+	{ AVAILABLE, "Available" },
+	{ BUSY, "Busy"},
+	{ OTP, "On the phone"},
+	{ IDLE, "Idle"},
+	{ AWAY, "Away"},
+	{ BRB, "Be right back"},
+	{ OFFLINE, "Offline"}
+    };
+
+    printf("\n"
+	   "Choices:\n");
+    for (i=0; i<PJ_ARRAY_SIZE(opts); ++i) {
+	printf("  %d  %s\n", opts[i].id+1, opts[i].name);
+    }
+
+    if (!simple_input("Select status", menuin, sizeof(menuin)))
+	return;
+
+    choice = atoi(menuin) - 1;
+    if (choice < 0 || choice >= OPT_MAX) {
+	puts("Invalid selection");
+	return;
+    }
+
+    pj_bzero(&elem, sizeof(elem));
+    elem.type = PJRPID_ELEMENT_TYPE_PERSON;
+
+    online_status = PJ_TRUE;
+
+    switch (choice) {
+    case AVAILABLE:
+	break;
+    case BUSY:
+	elem.activity = PJRPID_ACTIVITY_BUSY;
+	elem.note = pj_str("Busy");
+	break;
+    case OTP:
+	elem.activity = PJRPID_ACTIVITY_BUSY;
+	elem.note = pj_str("On the phone");
+	break;
+    case IDLE:
+	elem.activity = PJRPID_ACTIVITY_UNKNOWN;
+	elem.note = pj_str("Idle");
+	break;
+    case AWAY:
+	elem.activity = PJRPID_ACTIVITY_AWAY;
+	elem.note = pj_str("Away");
+	break;
+    case BRB:
+	elem.activity = PJRPID_ACTIVITY_UNKNOWN;
+	elem.note = pj_str("Be right back");
+	break;
+    case OFFLINE:
+	online_status = PJ_FALSE;
+	break;
+    }
+
+    pjsua_acc_set_online_status2(current_acc, online_status, &elem);
+}
+
+/*
+ * List the ports in conference bridge
+ */
+static void ui_conf_list()
+{
+    unsigned i, count;
+    pjsua_conf_port_id id[PJSUA_MAX_CALLS];
+
+    printf("Conference ports:\n");
+
+    count = PJ_ARRAY_SIZE(id);
+    pjsua_enum_conf_ports(id, &count);
+
+    for (i=0; i<count; ++i) {
+	char txlist[PJSUA_MAX_CALLS*4+10];
+	unsigned j;
+	pjsua_conf_port_info info;
+
+	pjsua_conf_get_port_info(id[i], &info);
+
+	txlist[0] = '\0';
+	for (j=0; j<info.listener_cnt; ++j) {
+	    char s[10];
+	    pj_ansi_snprintf(s, sizeof(s), "#%d ", info.listeners[j]);
+	    pj_ansi_strcat(txlist, s);
+	}
+	printf("Port #%02d[%2dKHz/%dms/%d] %20.*s  transmitting to: %s\n", 
+	       info.slot_id, 
+	       info.clock_rate/1000,
+	       info.samples_per_frame*1000/info.channel_count/info.clock_rate,
+	       info.channel_count,
+	       (int)info.name.slen, 
+	       info.name.ptr,
+	       txlist);
+
+    }
+    puts("");
+}
+
+static void ui_conf_connect(char menuin[])
+{
+    char tmp[10], src_port[10], dst_port[10];
+    pj_status_t status;
+    int cnt;
+    const char *src_title, *dst_title;
+
+    cnt = sscanf(menuin, "%s %s %s", tmp, src_port, dst_port);
+
+    if (cnt != 3) {
+	ui_conf_list();
+
+	src_title = (menuin[1]=='c'? "Connect src port #":
+				     "Disconnect src port #");
+	dst_title = (menuin[1]=='c'? "To dst port #":"From dst port #");
+
+	if (!simple_input(src_title, src_port, sizeof(src_port)))
+	    return;
+
+	if (!simple_input(dst_title, dst_port, sizeof(dst_port)))
+	    return;
+    }
+
+    if (menuin[1]=='c') {
+	status = pjsua_conf_connect(my_atoi(src_port), my_atoi(dst_port));
+    } else {
+	status = pjsua_conf_disconnect(my_atoi(src_port), my_atoi(dst_port));
+    }
+    if (status == PJ_SUCCESS) {
+	puts("Success");
+    } else {
+	puts("ERROR!!");
+    }
+}
+
+static void ui_adjust_volume()
+{
+    char buf[128];
+    char text[128];
+    sprintf(buf, "Adjust mic level: [%4.1fx] ", app_config.mic_level);
+    if (simple_input(buf,text,sizeof(text))) {
+	char *err;
+	app_config.mic_level = (float)strtod(text, &err);
+	pjsua_conf_adjust_rx_level(0, app_config.mic_level);
+    }
+    sprintf(buf, "Adjust speaker level: [%4.1fx] ", app_config.speaker_level);
+    if (simple_input(buf,text,sizeof(text))) {
+	char *err;
+	app_config.speaker_level = (float)strtod(text, &err);
+	pjsua_conf_adjust_tx_level(0, app_config.speaker_level);
+    }
+}
+
+static void ui_dump_call_quality()
+{
+    if (current_call != PJSUA_INVALID_ID) {
+	log_call_dump(current_call);
+    } else {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    }
+}
+
+static void ui_dump_configuration()
+{
+    char settings[2000];
+    int len;
+
+    len = write_settings(&app_config, settings, sizeof(settings));
+    if (len < 1)
+	PJ_LOG(1,(THIS_FILE, "Error: not enough buffer"));
+    else
+	PJ_LOG(3,(THIS_FILE, "Dumping configuration (%d bytes):\n%s\n",	
+		  len, settings));	
+}
+
+static void ui_write_settings()
+{
+    char settings[2000];
+    int len;
+    char buf[128];
+
+    len = write_settings(&app_config, settings, sizeof(settings));
+    if (len < 1)
+	PJ_LOG(1,(THIS_FILE, "Error: not enough buffer"));
+    else {
+	pj_oshandle_t fd;
+	pj_status_t status;
+
+	status = pj_file_open(app_config.pool, buf, PJ_O_WRONLY, &fd);
+	if (status != PJ_SUCCESS) {
+	    pjsua_perror(THIS_FILE, "Unable to open file", status);
+	} else {
+	    pj_ssize_t size = len;
+	    pj_file_write(fd, settings, &size);
+	    pj_file_close(fd);
+
+	    printf("Settings successfully written to '%s'\n", buf);
+	}
+    }
+}
+
+/*
+ * Dump application states.
+ */
+static void ui_app_dump(pj_bool_t detail)
+{
+    pjsua_dump(detail);
+}
+
+static void ui_call_redirect(char menuin[])
+{
+    if (current_call == PJSUA_INVALID_ID) {
+	PJ_LOG(3,(THIS_FILE, "No current call"));
+    } else {
+	if (!pjsua_call_is_active(current_call)) {
+	    PJ_LOG(1,(THIS_FILE, "Call %d has gone", current_call));
+	} else if (menuin[1] == 'a') {
+	    pjsua_call_process_redirect(current_call, 
+		PJSIP_REDIRECT_ACCEPT_REPLACE);
+	} else if (menuin[1] == 'A') {
+	    pjsua_call_process_redirect(current_call, 
+		PJSIP_REDIRECT_ACCEPT);
+	} else if (menuin[1] == 'r') {
+	    pjsua_call_process_redirect(current_call,
+		PJSIP_REDIRECT_REJECT);
+	} else {
+	    pjsua_call_process_redirect(current_call,
+		PJSIP_REDIRECT_STOP);
+	}
+    }
+}
+
+/*
+ * Main "user interface" loop.
+ */
+void console_app_main(const pj_str_t *uri_to_call, pj_bool_t *app_restart)
+{    
+    char menuin[80];    
+    char buf[128];    
+
+    pjsua_call_setting_default(&call_opt);
+    call_opt.aud_cnt = app_config.aud_cnt;
+    call_opt.vid_cnt = app_config.vid.vid_cnt;
+
+    /* If user specifies URI to call, then call the URI */
+    if (uri_to_call->slen) {
+	pjsua_call_make_call( current_acc, uri_to_call, &call_opt, 
+			      NULL, NULL, NULL);
+    }
+
+    keystroke_help(current_call);
+
+    for (;;) {
+
+	printf(">>> ");
+	fflush(stdout);
+
+	if (fgets(menuin, sizeof(menuin), stdin) == NULL) {
+	    /* 
+	     * Be friendly to users who redirect commands into
+	     * program, when file ends, resume with kbd.
+	     * If exit is desired end script with q for quit
+	     */
+ 	    /* Reopen stdin/stdout/stderr to /dev/console */
+#if defined(PJ_WIN32) && PJ_WIN32!=0
+	    if (freopen ("CONIN$", "r", stdin) == NULL) {
+#else
+	    if (1) {
+#endif
+		puts("Cannot switch back to console from file redirection");
+		menuin[0] = 'q';
+		menuin[1] = '\0';
+	    } else {
+		puts("Switched back to console from file redirection");
+		continue;
+	    }
+	}
+
+	if (cmd_echo) {
+	    printf("%s", menuin);
+	}
+
+	/* Update call setting */
+	pjsua_call_setting_default(&call_opt);
+	call_opt.aud_cnt = app_config.aud_cnt;
+	call_opt.vid_cnt = app_config.vid.vid_cnt;
+
+	switch (menuin[0]) {
+
+	case 'm':
+	    /* Make call! : */
+	    ui_make_new_call();
+	    break;
+
+	case 'M':
+	    /* Make multiple calls! : */
+	    ui_make_multi_call();
+	    break;
+
+	case 'n':
+	    ui_detect_nat_type();
+	    break;
+
+	case 'i':
+	    /* Send instant messaeg */
+	    ui_send_instant_message();
+	    break;
+
+	case 'a':
+	    ui_answer_call();
+	    break;
+
+	case 'h':
+	    ui_hangup_call(menuin);
+	    break;
+
+	case ']':
+	case '[':
+	    /*
+	     * Cycle next/prev dialog.
+	     */
+	    ui_cycle_dialog(menuin);
+	    break;
+
+	case '>':
+	case '<':
+	    ui_cycle_account();
+	    break;
+
+	case '+':
+	    if (menuin[1] == 'b') {
+		ui_add_buddy();
+	    } else if (menuin[1] == 'a') {
+		ui_add_account(&app_config.rtp_cfg);
+	    } else {
+		printf("Invalid input %s\n", menuin);
+	    }
+	    break;
+
+	case '-':
+	    if (menuin[1] == 'b') {
+		ui_delete_buddy();
+	    } else if (menuin[1] == 'a') {
+		ui_delete_account();
+	    } else {
+		printf("Invalid input %s\n", menuin);
+	    }
+	    break;
+
+	case 'H':
+	    /*
+	     * Hold call.
+	     */
+	    ui_call_hold();
+	    break;
+
+	case 'v':	    
+#if PJSUA_HAS_VIDEO
+	    if (menuin[1]=='i' && menuin[2]=='d' && menuin[3]==' ') {
+		vid_handle_menu(menuin);
+	    } else
+#endif
+	    if (current_call != -1) {
+		/*
+		 * re-INVITE
+		 */
+		ui_call_reinvite();
+	    } else {
+		PJ_LOG(3,(THIS_FILE, "No current call"));
+	    }
+	    break;
+
+	case 'U':
+	    /*
+	     * Send UPDATE
+	     */
+	    ui_send_update();
+	    break;
+
+	case 'C':
+	    if (menuin[1] == 'p') {
+		ui_manage_codec_prio();
+	    }
+	    break;
+
+	case 'x':
+	    /*
+	     * Transfer call.
+	     */
+	    ui_call_transfer(app_config.no_refersub);
+	    break;
+
+	case 'X':
+	    /*
+	     * Transfer call with replaces.
+	     */
+	    ui_call_transfer_replaces(app_config.no_refersub);
+	    break;
+
+	case '#':
+	    /*
+	     * Send DTMF strings.
+	     */
+	    ui_send_dtmf_2833();
+	    break;
+
+	case '*':
+	    /* Send DTMF with INFO */
+	    ui_send_dtmf_info();
+	    break;
+
+	case 'S':
+	    /*
+	     * Send arbitrary request
+	     */
+	    ui_send_arbitrary_request();
+	    break;
+
+	case 'e':
+	    ui_echo(menuin);
+	    break;
+
+	case 's':	    
+	    ui_sleep(menuin);
+	    break;
+	    /* Continue below */
+
+	case 'u':
+	    /*
+	     * Subscribe/unsubscribe presence.
+	     */
+	    ui_subscribe(menuin);
+	    break;
+
+	case 'r':
+	    ui_register(menuin);
+	    break;
+	    
+	case 't':
+	    ui_toggle_state();
+	    break;
+
+	case 'T':
+	    ui_change_online_status();
+	    break;
+
+	case 'c':
+	    switch (menuin[1]) {
+	    case 'l':
+		ui_conf_list();
+		break;
+	    case 'c':
+	    case 'd':
+		ui_conf_connect(menuin);
+		break;
+	    }
+	    break;
+
+	case 'V':
+	    /* Adjust audio volume */	    
+	    ui_adjust_volume();
+	    break;
+
+	case 'd':
+	    if (menuin[1] == 'c') {
+		ui_dump_configuration();	
+	    } else if (menuin[1] == 'q') {
+		ui_dump_call_quality();
+	    } else {		
+		ui_app_dump(menuin[1]=='d');
+	    }
+	    break;
+
+	case 'f':
+	    if (simple_input("Enter output filename", buf, sizeof(buf))) {
+		ui_write_settings();		
+	    }
+	    break;
+
+	case 'L':   /* Restart */
+	    *app_restart = PJ_TRUE;
+	    /* Continues below */
+
+	case 'q':
+	    goto on_exit;
+
+	case 'R':	    
+	    ui_call_redirect(menuin);
+	    break;
+
+	default:
+	    if (menuin[0] != '\n' && menuin[0] != '\r') {
+		printf("Invalid input %s", menuin);
+	    }
+	    keystroke_help();
+	    break;
+	}
+    }
+
+on_exit:
+    ;
+}
+
+void start_ui_main(pj_str_t *uri_to_call, pj_bool_t *app_restart)
+{
+    pj_status_t status;    
+    *app_restart = PJ_FALSE;
+
+    status = pjsua_start();
+    if (status != PJ_SUCCESS)
+	return;	    
+
+    setup_signal_handler();
+
+    /* If user specifies URI to call, then call the URI */
+    if (uri_to_call->slen) {
+	pjsua_call_make_call(current_acc, uri_to_call, &call_opt, NULL, 
+			     NULL, NULL);
+    }    
+
+    console_app_main(uri_to_call, app_restart);
+}
Index: project/trunk/pjsip-apps/src/pjsua/pjsua_ui_cmd.c
===================================================================
--- /pjproject/trunk/pjsip-apps/src/pjsua/pjsua_ui_cmd.c	(revision 4460)
+++ 	(revision )
@@ -1,1940 +1,0 @@
-/* $Id$ */
-/* 
- * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
- * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.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 
- */
-
-#include <pjsua-lib/pjsua.h>
-#include "pjsua_cmd.h"
-
-#define THIS_FILE	"pjsua_ui_cmd.c"
-
-static pj_bool_t	cmd_echo;
-
-/*
- * Print buddy list.
- */
-static void print_buddy_list()
-{
-    pjsua_buddy_id ids[64];
-    int i;
-    unsigned count = PJ_ARRAY_SIZE(ids);
-
-    puts("Buddy list:");
-
-    pjsua_enum_buddies(ids, &count);
-
-    if (count == 0)
-	puts(" -none-");
-    else {
-	for (i=0; i<(int)count; ++i) {
-	    pjsua_buddy_info info;
-
-	    if (pjsua_buddy_get_info(ids[i], &info) != PJ_SUCCESS)
-		continue;
-
-	    printf(" [%2d] <%.*s>  %.*s\n", 
-		    ids[i]+1, 
-		    (int)info.status_text.slen,
-		    info.status_text.ptr, 
-		    (int)info.uri.slen,
-		    info.uri.ptr);
-	}
-    }
-    puts("");
-}
-
-/*
- * Input URL.
- */
-static void ui_input_url(const char *title, char *buf, int len, 
-			 input_result *result)
-{
-    result->nb_result = NO_NB;
-    result->uri_result = NULL;
-
-    print_buddy_list();
-
-    printf("Choices:\n"
-	   "   0         For current dialog.\n"
-	   "  -1         All %d buddies in buddy list\n"
-	   "  [1 -%2d]    Select from buddy list\n"
-	   "  URL        An URL\n"
-	   "  <Enter>    Empty input (or 'q') to cancel\n"
-	   , pjsua_get_buddy_count(), pjsua_get_buddy_count());
-    printf("%s: ", title);
-
-    fflush(stdout);
-    if (fgets(buf, len, stdin) == NULL)
-	return;
-    len = strlen(buf);
-
-    /* Left trim */
-    while (pj_isspace(*buf)) {
-	++buf;
-	--len;
-    }
-
-    /* Remove trailing newlines */
-    while (len && (buf[len-1] == '\r' || buf[len-1] == '\n'))
-	buf[--len] = '\0';
-
-    if (len == 0 || buf[0]=='q')
-	return;
-
-    if (pj_isdigit(*buf) || *buf=='-') {
-	
-	int i;
-	
-	if (*buf=='-')
-	    i = 1;
-	else
-	    i = 0;
-
-	for (; i<len; ++i) {
-	    if (!pj_isdigit(buf[i])) {
-		puts("Invalid input");
-		return;
-	    }
-	}
-
-	result->nb_result = my_atoi(buf);
-
-	if (result->nb_result >= 0 && 
-	    result->nb_result <= (int)pjsua_get_buddy_count()) 
-	{
-	    return;
-	}
-	if (result->nb_result == -1)
-	    return;
-
-	puts("Invalid input");
-	result->nb_result = NO_NB;
-	return;
-
-    } else {
-	pj_status_t status;
-
-	if ((status=pjsua_verify_url(buf)) != PJ_SUCCESS) {
-	    pjsua_perror(THIS_FILE, "Invalid URL", status);
-	    return;
-	}
-
-	result->uri_result = buf;
-    }
-}
-
-static pj_bool_t simple_input(const char *title, char *buf, pj_size_t len)
-{
-    char *p;
-
-    printf("%s (empty to cancel): ", title); fflush(stdout);
-    if (fgets(buf, len, stdin) == NULL)
-	return PJ_FALSE;
-
-    /* Remove trailing newlines. */
-    for (p=buf; ; ++p) {
-	if (*p=='\r' || *p=='\n') *p='\0';
-	else if (!*p) break;
-    }
-
-    if (!*buf)
-	return PJ_FALSE;
-    
-    return PJ_TRUE;
-}
-
-/*
- * Print account status.
- */
-static void print_acc_status(int acc_id)
-{
-    char buf[80];
-    pjsua_acc_info info;
-
-    pjsua_acc_get_info(acc_id, &info);
-
-    if (!info.has_registration) {
-	pj_ansi_snprintf(buf, sizeof(buf), "%.*s", 
-			 (int)info.status_text.slen,
-			 info.status_text.ptr);
-
-    } else {
-	pj_ansi_snprintf(buf, sizeof(buf),
-			 "%d/%.*s (expires=%d)",
-			 info.status,
-			 (int)info.status_text.slen,
-			 info.status_text.ptr,
-			 info.expires);
-
-    }
-
-    printf(" %c[%2d] %.*s: %s\n", (acc_id==current_acc?'*':' '),
-	   acc_id,  (int)info.acc_uri.slen, info.acc_uri.ptr, buf);
-    printf("       Online status: %.*s\n", 
-	(int)info.online_status_text.slen,
-	info.online_status_text.ptr);
-}
-
-/*
- * Show a bit of help.
- */
-static void keystroke_help()
-{
-    pjsua_acc_id acc_ids[16];
-    unsigned count = PJ_ARRAY_SIZE(acc_ids);
-    int i;
-
-    printf(">>>>\n");
-
-    pjsua_enum_accs(acc_ids, &count);
-
-    printf("Account list:\n");
-    for (i=0; i<(int)count; ++i)
-	print_acc_status(acc_ids[i]);
-
-    print_buddy_list();
-    
-    //puts("Commands:");
-    puts("+=============================================================================+");
-    puts("|       Call Commands:         |   Buddy, IM & Presence:  |     Account:      |");
-    puts("|                              |                          |                   |");
-    puts("|  m  Make new call            | +b  Add new buddy       .| +a  Add new accnt |");
-    puts("|  M  Make multiple calls      | -b  Delete buddy         | -a  Delete accnt. |");
-    puts("|  a  Answer call              |  i  Send IM              | !a  Modify accnt. |");
-    puts("|  h  Hangup call  (ha=all)    |  s  Subscribe presence   | rr  (Re-)register |");
-    puts("|  H  Hold call                |  u  Unsubscribe presence | ru  Unregister    |");
-    puts("|  v  re-inVite (release hold) |  t  ToGgle Online status |  >  Cycle next ac.|");
-    puts("|  U  send UPDATE              |  T  Set online status    |  <  Cycle prev ac.|");
-    puts("| ],[ Select next/prev call    +--------------------------+-------------------+");
-    puts("|  x  Xfer call                |      Media Commands:     |  Status & Config: |");
-    puts("|  X  Xfer with Replaces       |                          |                   |");
-    puts("|  #  Send RFC 2833 DTMF       | cl  List ports           |  d  Dump status   |");
-    puts("|  *  Send DTMF with INFO      | cc  Connect port         | dd  Dump detailed |");
-    puts("| dq  Dump curr. call quality  | cd  Disconnect port      | dc  Dump config   |");
-    puts("|                              |  V  Adjust audio Volume  |  f  Save config   |");
-    puts("|  S  Send arbitrary REQUEST   | Cp  Codec priorities     |                   |");
-    puts("+-----------------------------------------------------------------------------+");
-#if PJSUA_HAS_VIDEO
-    puts("| Video: \"vid help\" for more info                                             |");
-    puts("+-----------------------------------------------------------------------------+");
-#endif
-    puts("|  q  QUIT   L  ReLoad   sleep MS   echo [0|1|txt]     n: detect NAT type     |");
-    puts("+=============================================================================+");
-
-    i = pjsua_call_get_count();
-    printf("You have %d active call%s\n", i, (i>1?"s":""));
-
-    if (current_call != PJSUA_INVALID_ID) {
-	pjsua_call_info ci;
-	if (pjsua_call_get_info(current_call, &ci)==PJ_SUCCESS)
-	    printf("Current call id=%d to %.*s [%.*s]\n", current_call,
-		   (int)ci.remote_info.slen, ci.remote_info.ptr,
-		   (int)ci.state_text.slen, ci.state_text.ptr);
-    }
-}
-
-/* Help screen for video */
-#if PJSUA_HAS_VIDEO
-static void vid_show_help()
-{
-    pj_bool_t vid_enabled = (app_config.vid.vid_cnt > 0);
-
-    puts("+=============================================================================+");
-    puts("|                            Video commands:                                  |");
-    puts("|                                                                             |");
-    puts("| vid help                  Show this help screen                             |");
-    puts("| vid enable|disable        Enable or disable video in next offer/answer      |");
-    puts("| vid acc show              Show current account video settings               |");
-    puts("| vid acc autorx on|off     Automatically show incoming video on/off          |");
-    puts("| vid acc autotx on|off     Automatically offer video on/off                  |");
-    puts("| vid acc cap ID            Set default capture device for current acc        |");
-    puts("| vid acc rend ID           Set default renderer device for current acc       |");
-    puts("| vid call rx on|off N      Enable/disable video RX for stream N in curr call |");
-    puts("| vid call tx on|off N      Enable/disable video TX for stream N in curr call |");
-    puts("| vid call add              Add video stream for current call                 |");
-    puts("| vid call enable|disable N Enable/disable stream #N in current call          |");
-    puts("| vid call cap N ID         Set capture dev ID for stream #N in current call  |");
-    puts("| vid dev list              List all video devices                            |");
-    puts("| vid dev refresh           Refresh video device list                         |");
-    puts("| vid dev prev on|off ID    Enable/disable preview for specified device ID    |");
-    puts("| vid codec list            List video codecs                                 |");
-    puts("| vid codec prio ID PRIO    Set codec ID priority to PRIO                     |");
-    puts("| vid codec fps ID NUM DEN  Set codec ID framerate to (NUM/DEN) fps           |");
-    puts("| vid codec bw ID AVG MAX   Set codec ID bitrate to AVG & MAX kbps            |");
-    puts("| vid codec size ID W H     Set codec ID size/resolution to W x H             |");
-    puts("| vid win list              List all active video windows                     |");
-    puts("| vid win arrange           Auto arrange windows                              |");
-    puts("| vid win show|hide ID      Show/hide the specified video window ID           |");
-    puts("| vid win move ID X Y       Move window ID to position X,Y                    |");
-    puts("| vid win resize ID w h     Resize window ID to the specified width, height   |");
-    puts("+=============================================================================+");
-    printf("| Video will be %s in the next offer/answer %s                            |\n",
-	   (vid_enabled? "enabled" : "disabled"), (vid_enabled? " " : ""));
-    puts("+=============================================================================+");
-}
-
-static void vid_handle_menu(char *menuin)
-{
-    char *argv[8];
-    int argc = 0;
-
-    /* Tokenize */
-    argv[argc] = strtok(menuin, " \t\r\n");
-    while (argv[argc] && *argv[argc]) {
-	argc++;
-	argv[argc] = strtok(NULL, " \t\r\n");
-    }
-
-    if (argc == 1 || strcmp(argv[1], "help")==0) {
-	vid_show_help();
-    } else if (argc == 2 && (strcmp(argv[1], "enable")==0 ||
-			     strcmp(argv[1], "disable")==0))
-    {
-	pj_bool_t enabled = (strcmp(argv[1], "enable")==0);
-	app_config.vid.vid_cnt = (enabled ? 1 : 0);
-	PJ_LOG(3,(THIS_FILE, "Video will be %s in next offer/answer",
-		  (enabled?"enabled":"disabled")));
-    } else if (strcmp(argv[1], "acc")==0) {
-	pjsua_acc_config acc_cfg;
-	pj_bool_t changed = PJ_FALSE;
-
-	pjsua_acc_get_config(current_acc, &acc_cfg);
-
-	if (argc == 3 && strcmp(argv[2], "show")==0) {
-	    app_config_show_video(current_acc, &acc_cfg);
-	} else if (argc == 4 && strcmp(argv[2], "autorx")==0) {
-	    int on = (strcmp(argv[3], "on")==0);
-	    acc_cfg.vid_in_auto_show = on;
-	    changed = PJ_TRUE;
-	} else if (argc == 4 && strcmp(argv[2], "autotx")==0) {
-	    int on = (strcmp(argv[3], "on")==0);
-	    acc_cfg.vid_out_auto_transmit = on;
-	    changed = PJ_TRUE;
-	} else if (argc == 4 && strcmp(argv[2], "cap")==0) {
-	    int dev = atoi(argv[3]);
-	    acc_cfg.vid_cap_dev = dev;
-	    changed = PJ_TRUE;
-	} else if (argc == 4 && strcmp(argv[2], "rend")==0) {
-	    int dev = atoi(argv[3]);
-	    acc_cfg.vid_rend_dev = dev;
-	    changed = PJ_TRUE;
-	} else {
-	    goto on_error;
-	}
-
-	if (changed) {
-	    pj_status_t status = pjsua_acc_modify(current_acc, &acc_cfg);
-	    if (status != PJ_SUCCESS)
-		PJ_PERROR(1,(THIS_FILE, status, "Error modifying account %d",
-			     current_acc));
-	}
-
-    } else if (strcmp(argv[1], "call")==0) {
-	pjsua_call_vid_strm_op_param param;
-	pj_status_t status = PJ_SUCCESS;
-
-	pjsua_call_vid_strm_op_param_default(&param);
-
-	if (argc == 5 && strcmp(argv[2], "rx")==0) {
-	    pjsua_stream_info si;
-	    pj_bool_t on = (strcmp(argv[3], "on") == 0);
-
-	    param.med_idx = atoi(argv[4]);
-	    if (pjsua_call_get_stream_info(current_call, param.med_idx, &si) ||
-		si.type != PJMEDIA_TYPE_VIDEO)
-	    {
-		PJ_PERROR(1,(THIS_FILE, PJ_EINVAL, "Invalid stream"));
-		return;
-	    }
-
-	    if (on) param.dir = (si.info.vid.dir | PJMEDIA_DIR_DECODING);
-	    else param.dir = (si.info.vid.dir & PJMEDIA_DIR_ENCODING);
-
-	    status = pjsua_call_set_vid_strm(current_call,
-	                                     PJSUA_CALL_VID_STRM_CHANGE_DIR,
-	                                     &param);
-	}
-	else if (argc == 5 && strcmp(argv[2], "tx")==0) {
-	    pj_bool_t on = (strcmp(argv[3], "on") == 0);
-	    pjsua_call_vid_strm_op op = on? PJSUA_CALL_VID_STRM_START_TRANSMIT :
-					    PJSUA_CALL_VID_STRM_STOP_TRANSMIT;
-
-	    param.med_idx = atoi(argv[4]);
-
-	    status = pjsua_call_set_vid_strm(current_call, op, &param);
-	}
-	else if (argc == 3 && strcmp(argv[2], "add")==0) {
-	    status = pjsua_call_set_vid_strm(current_call,
-	                                     PJSUA_CALL_VID_STRM_ADD, NULL);
-	}
-	else if (argc >= 3 && 
-		 (strcmp(argv[2], "disable")==0 || strcmp(argv[2], "enable")==0))
-	{
-	    pj_bool_t enable = (strcmp(argv[2], "enable") == 0);
-	    pjsua_call_vid_strm_op op = enable? PJSUA_CALL_VID_STRM_CHANGE_DIR :
-						PJSUA_CALL_VID_STRM_REMOVE;
-
-	    param.med_idx = argc >= 4? atoi(argv[3]) : -1;
-	    param.dir = PJMEDIA_DIR_ENCODING_DECODING;
-	    status = pjsua_call_set_vid_strm(current_call, op, &param);
-	}
-	else if (argc >= 3 && strcmp(argv[2], "cap")==0) {
-	    param.med_idx = argc >= 4? atoi(argv[3]) : -1;
-	    param.cap_dev = argc >= 5? atoi(argv[4]) : PJMEDIA_VID_DEFAULT_CAPTURE_DEV;
-	    status = pjsua_call_set_vid_strm(current_call,
-	                                     PJSUA_CALL_VID_STRM_CHANGE_CAP_DEV,
-	                                     &param);
-	} else
-	    goto on_error;
-
-	if (status != PJ_SUCCESS) {
-	    PJ_PERROR(1,(THIS_FILE, status, "Error modifying video stream"));
-	}
-
-    } else if (argc >= 3 && strcmp(argv[1], "dev")==0) {
-	if (strcmp(argv[2], "list")==0) {
-	    vid_list_devs();
-	} else if (strcmp(argv[2], "refresh")==0) {
-	    pjmedia_vid_dev_refresh();
-	} else if (strcmp(argv[2], "prev")==0) {
-	    if (argc != 5) {
-		goto on_error;
-	    } else {
-		pj_bool_t on = (strcmp(argv[3], "on") == 0);
-		int dev_id = atoi(argv[4]);
-		if (on) {
-                    pjsua_vid_preview_param param;
-
-                    pjsua_vid_preview_param_default(&param);
-                    param.wnd_flags = PJMEDIA_VID_DEV_WND_BORDER |
-                                      PJMEDIA_VID_DEV_WND_RESIZABLE;
-		    pjsua_vid_preview_start(dev_id, &param);
-		    arrange_window(pjsua_vid_preview_get_win(dev_id));
-		} else {
-		    pjsua_vid_win_id wid;
-		    wid = pjsua_vid_preview_get_win(dev_id);
-		    if (wid != PJSUA_INVALID_ID) {
-			/* Preview window hiding once it is stopped is
-			 * responsibility of app */
-			pjsua_vid_win_set_show(wid, PJ_FALSE);
-			pjsua_vid_preview_stop(dev_id);
-		    }
-		}
-	    }
-	} else
-	    goto on_error;
-    } else if (strcmp(argv[1], "win")==0) {
-	pj_status_t status = PJ_SUCCESS;
-
-	if (argc==3 && strcmp(argv[2], "list")==0) {
-	    pjsua_vid_win_id wids[PJSUA_MAX_VID_WINS];
-	    unsigned i, cnt = PJ_ARRAY_SIZE(wids);
-
-	    pjsua_vid_enum_wins(wids, &cnt);
-
-	    PJ_LOG(3,(THIS_FILE, "Found %d video windows:", cnt));
-	    PJ_LOG(3,(THIS_FILE, "WID show    pos       size"));
-	    PJ_LOG(3,(THIS_FILE, "------------------------------"));
-	    for (i = 0; i < cnt; ++i) {
-		pjsua_vid_win_info wi;
-		pjsua_vid_win_get_info(wids[i], &wi);
-		PJ_LOG(3,(THIS_FILE, "%3d   %c  (%d,%d)  %dx%d",
-			  wids[i], (wi.show?'Y':'N'), wi.pos.x, wi.pos.y,
-			  wi.size.w, wi.size.h));
-	    }
-	} else if (argc==4 && (strcmp(argv[2], "show")==0 ||
-			       strcmp(argv[2], "hide")==0))
-	{
-	    pj_bool_t show = (strcmp(argv[2], "show")==0);
-	    pjsua_vid_win_id wid = atoi(argv[3]);
-	    status = pjsua_vid_win_set_show(wid, show);
-	} else if (argc==6 && strcmp(argv[2], "move")==0) {
-	    pjsua_vid_win_id wid = atoi(argv[3]);
-	    pjmedia_coord pos;
-
-	    pos.x = atoi(argv[4]);
-	    pos.y = atoi(argv[5]);
-	    status = pjsua_vid_win_set_pos(wid, &pos);
-	} else if (argc==6 && strcmp(argv[2], "resize")==0) {
-	    pjsua_vid_win_id wid = atoi(argv[3]);
-	    pjmedia_rect_size size;
-
-	    size.w = atoi(argv[4]);
-	    size.h = atoi(argv[5]);
-	    status = pjsua_vid_win_set_size(wid, &size);
-	} else if (argc==3 && strcmp(argv[2], "arrange")==0) {
-	    arrange_window(PJSUA_INVALID_ID);
-	} else
-	    goto on_error;
-
-	if (status != PJ_SUCCESS) {
-	    PJ_PERROR(1,(THIS_FILE, status, "Window operation error"));
-	}
-
-    } else if (strcmp(argv[1], "codec")==0) {
-	pjsua_codec_info ci[PJMEDIA_CODEC_MGR_MAX_CODECS];
-	unsigned count = PJ_ARRAY_SIZE(ci);
-	pj_status_t status;
-
-	if (argc==3 && strcmp(argv[2], "list")==0) {
-	    status = pjsua_vid_enum_codecs(ci, &count);
-	    if (status != PJ_SUCCESS) {
-		PJ_PERROR(1,(THIS_FILE, status, "Error enumerating codecs"));
-	    } else {
-		unsigned i;
-		PJ_LOG(3,(THIS_FILE, "Found %d video codecs:", count));
-		PJ_LOG(3,(THIS_FILE, "codec id      prio  fps    bw(kbps)   size"));
-		PJ_LOG(3,(THIS_FILE, "------------------------------------------"));
-		for (i=0; i<count; ++i) {
-		    pjmedia_vid_codec_param cp;
-		    pjmedia_video_format_detail *vfd;
-
-		    status = pjsua_vid_codec_get_param(&ci[i].codec_id, &cp);
-		    if (status != PJ_SUCCESS)
-			continue;
-
-		    vfd = pjmedia_format_get_video_format_detail(&cp.enc_fmt,
-								 PJ_TRUE);
-		    PJ_LOG(3,(THIS_FILE, "%.*s%.*s %3d %7.2f  %4d/%4d  %dx%d", 
-			      (int)ci[i].codec_id.slen, ci[i].codec_id.ptr,
-			      13-(int)ci[i].codec_id.slen, "                ",
-			      ci[i].priority,
-			      (vfd->fps.num*1.0/vfd->fps.denum),
-			      vfd->avg_bps/1000, vfd->max_bps/1000,
-			      vfd->size.w, vfd->size.h));
-		}
-	    }
-	} else if (argc==5 && strcmp(argv[2], "prio")==0) {
-	    pj_str_t cid;
-	    int prio;
-	    cid = pj_str(argv[3]);
-	    prio = atoi(argv[4]);
-	    status = pjsua_vid_codec_set_priority(&cid, (pj_uint8_t)prio);
-	    if (status != PJ_SUCCESS)
-		PJ_PERROR(1,(THIS_FILE, status, "Set codec priority error"));
-	} else if (argc==6 && strcmp(argv[2], "fps")==0) {
-	    pjmedia_vid_codec_param cp;
-	    pj_str_t cid;
-	    int M, N;
-	    cid = pj_str(argv[3]);
-	    M = atoi(argv[4]);
-	    N = atoi(argv[5]);
-	    status = pjsua_vid_codec_get_param(&cid, &cp);
-	    if (status == PJ_SUCCESS) {
-		cp.enc_fmt.det.vid.fps.num = M;
-		cp.enc_fmt.det.vid.fps.denum = N;
-		status = pjsua_vid_codec_set_param(&cid, &cp);
-	    }
-	    if (status != PJ_SUCCESS)
-		PJ_PERROR(1,(THIS_FILE, status, "Set codec framerate error"));
-	} else if (argc==6 && strcmp(argv[2], "bw")==0) {
-	    pjmedia_vid_codec_param cp;
-	    pj_str_t cid;
-	    int M, N;
-	    cid = pj_str(argv[3]);
-	    M = atoi(argv[4]);
-	    N = atoi(argv[5]);
-	    status = pjsua_vid_codec_get_param(&cid, &cp);
-	    if (status == PJ_SUCCESS) {
-		cp.enc_fmt.det.vid.avg_bps = M * 1000;
-		cp.enc_fmt.det.vid.max_bps = N * 1000;
-		status = pjsua_vid_codec_set_param(&cid, &cp);
-	    }
-	    if (status != PJ_SUCCESS)
-		PJ_PERROR(1,(THIS_FILE, status, "Set codec bitrate error"));
-	} else if (argc==6 && strcmp(argv[2], "size")==0) {
-	    pjmedia_vid_codec_param cp;
-	    pj_str_t cid;
-	    int M, N;
-	    cid = pj_str(argv[3]);
-	    M = atoi(argv[4]);
-	    N = atoi(argv[5]);
-	    status = pjsua_vid_codec_get_param(&cid, &cp);
-	    if (status == PJ_SUCCESS) {
-		cp.enc_fmt.det.vid.size.w = M;
-		cp.enc_fmt.det.vid.size.h = N;
-		status = pjsua_vid_codec_set_param(&cid, &cp);
-	    }
-	    if (status != PJ_SUCCESS)
-		PJ_PERROR(1,(THIS_FILE, status, "Set codec size error"));
-	} else
-	    goto on_error;
-    } else
-	goto on_error;
-
-    return;
-
-on_error:
-    PJ_LOG(1,(THIS_FILE, "Invalid command, use 'vid help'"));
-}
-
-#endif /* PJSUA_HAS_VIDEO */
-
-/** UI Command **/
-static void ui_make_new_call()
-{    
-    char buf[128];
-    pjsua_msg_data msg_data;
-    input_result result;
-    pj_str_t tmp;
-
-    printf("(You currently have %d calls)\n", pjsua_call_get_count());
-    
-    ui_input_url("Make call", buf, sizeof(buf), &result);
-    if (result.nb_result != NO_NB) {
-
-	if (result.nb_result == -1 || result.nb_result == 0) {
-	    puts("You can't do that with make call!");
-	    return;
-	} else {
-	    pjsua_buddy_info binfo;
-	    pjsua_buddy_get_info(result.nb_result-1, &binfo);
-	    tmp.ptr = buf;
-	    pj_strncpy(&tmp, &binfo.uri, sizeof(buf));
-	}
-
-    } else if (result.uri_result) {
-	tmp = pj_str(result.uri_result);
-    } else {
-	tmp.slen = 0;
-    }
-
-    pjsua_msg_data_init(&msg_data);
-    TEST_MULTIPART(&msg_data);
-    pjsua_call_make_call(current_acc, &tmp, &call_opt, NULL, 
-			 &msg_data, &current_call);
-}
-
-static void ui_make_multi_call()
-{
-    char menuin[32];
-    int count;
-    char buf[128];
-    input_result result;
-    pj_str_t tmp;
-    int i;
-
-    printf("(You currently have %d calls)\n", pjsua_call_get_count());
-
-    if (!simple_input("Number of calls", menuin, sizeof(menuin)))
-	return;
-
-    count = my_atoi(menuin);
-    if (count < 1)
-	return;
-
-    ui_input_url("Make call", buf, sizeof(buf), &result);
-    if (result.nb_result != NO_NB) {
-	pjsua_buddy_info binfo;
-	if (result.nb_result == -1 || result.nb_result == 0) {
-	    puts("You can't do that with make call!");
-	    return;
-	}
-	pjsua_buddy_get_info(result.nb_result-1, &binfo);
-	tmp.ptr = buf;
-	pj_strncpy(&tmp, &binfo.uri, sizeof(buf));
-    } else {
-	tmp = pj_str(result.uri_result);
-    }
-
-    for (i=0; i<my_atoi(menuin); ++i) {
-	pj_status_t status;
-
-	status = pjsua_call_make_call(current_acc, &tmp, &call_opt, NULL,
-	    NULL, NULL);
-	if (status != PJ_SUCCESS)
-	    break;
-    }
-}
-
-static void ui_detect_nat_type()
-{
-    int i = pjsua_detect_nat_type();
-    if (i != PJ_SUCCESS)
-	pjsua_perror(THIS_FILE, "Error", i);
-}
-
-static void ui_send_instant_message()
-{
-    char *uri = NULL;
-    /* i is for call index to send message, if any */
-    int i = -1;
-    input_result result;
-    char buf[128];
-    char text[128];
-    pj_str_t tmp;
-
-    /* Input destination. */
-    ui_input_url("Send IM to", buf, sizeof(buf), &result);
-    if (result.nb_result != NO_NB) {
-
-	if (result.nb_result == -1) {
-	    puts("You can't send broadcast IM like that!");
-	    return;
-
-	} else if (result.nb_result == 0) {
-	    i = current_call;
-	} else {
-	    pjsua_buddy_info binfo;
-	    pjsua_buddy_get_info(result.nb_result-1, &binfo);
-	    tmp.ptr = buf;
-	    pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(buf));
-	    uri = buf;
-	}
-
-    } else if (result.uri_result) {
-	uri = result.uri_result;
-    }
-
-
-    /* Send typing indication. */
-    if (i != -1)
-	pjsua_call_send_typing_ind(i, PJ_TRUE, NULL);
-    else {
-	pj_str_t tmp_uri = pj_str(uri);
-	pjsua_im_typing(current_acc, &tmp_uri, PJ_TRUE, NULL);
-    }
-
-    /* Input the IM . */
-    if (!simple_input("Message", text, sizeof(text))) {
-	/*
-	* Cancelled.
-	* Send typing notification too, saying we're not typing.
-	*/
-	if (i != -1)
-	    pjsua_call_send_typing_ind(i, PJ_FALSE, NULL);
-	else {
-	    pj_str_t tmp_uri = pj_str(uri);
-	    pjsua_im_typing(current_acc, &tmp_uri, PJ_FALSE, NULL);
-	}
-	return;
-    }
-
-    tmp = pj_str(text);
-
-    /* Send the IM */
-    if (i != -1)
-	pjsua_call_send_im(i, NULL, &tmp, NULL, NULL);
-    else {
-	pj_str_t tmp_uri = pj_str(uri);
-	pjsua_im_send(current_acc, &tmp_uri, NULL, &tmp, NULL, NULL);
-    }
-}
-
-static void ui_answer_call()
-{
-    pjsua_call_info call_info;
-    char buf[128];
-    pjsua_msg_data msg_data;
-
-    if (current_call != -1) {
-	pjsua_call_get_info(current_call, &call_info);
-    } else {
-	/* Make compiler happy */
-	call_info.role = PJSIP_ROLE_UAC;
-	call_info.state = PJSIP_INV_STATE_DISCONNECTED;
-    }
-
-    if (current_call == -1 || 
-	call_info.role != PJSIP_ROLE_UAS ||
-	call_info.state >= PJSIP_INV_STATE_CONNECTING)
-    {
-	puts("No pending incoming call");
-	fflush(stdout);
-	return;
-
-    } else {
-	int st_code;
-	char contact[120];
-	pj_str_t hname = { "Contact", 7 };
-	pj_str_t hvalue;
-	pjsip_generic_string_hdr hcontact;
-
-	if (!simple_input("Answer with code (100-699)", buf, sizeof(buf)))
-	    return;
-
-	st_code = my_atoi(buf);
-	if (st_code < 100)
-	    return;
-
-	pjsua_msg_data_init(&msg_data);
-
-	if (st_code/100 == 3) {
-	    if (!simple_input("Enter URL to be put in Contact", 
-		contact, sizeof(contact)))
-		return;
-	    hvalue = pj_str(contact);
-	    pjsip_generic_string_hdr_init2(&hcontact, &hname, &hvalue);
-
-	    pj_list_push_back(&msg_data.hdr_list, &hcontact);
-	}
-
-	/*
-	* Must check again!
-	* Call may have been disconnected while we're waiting for 
-	* keyboard input.
-	*/
-	if (current_call == -1) {
-	    puts("Call has been disconnected");
-	    fflush(stdout);
-	    return;
-	}
-
-	pjsua_call_answer2(current_call, &call_opt, st_code, NULL, &msg_data);
-    }    
-}
-
-static void ui_hangup_call(char menuin[])
-{
-    if (current_call == -1) {
-	puts("No current call");
-	fflush(stdout);
-	return;
-
-    } else if (menuin[1] == 'a') {
-	/* Hangup all calls */
-	pjsua_call_hangup_all();
-    } else {
-	/* Hangup current calls */
-	pjsua_call_hangup(current_call, 0, NULL, NULL);
-    }
-}
-
-static void ui_cycle_dialog(char menuin[])
-{
-    if (menuin[0] == ']') {
-	find_next_call();
-
-    } else {
-	find_prev_call();
-    }
-
-    if (current_call != -1) {
-	pjsua_call_info call_info;
-
-	pjsua_call_get_info(current_call, &call_info);
-	PJ_LOG(3,(THIS_FILE,"Current dialog: %.*s", 
-	    (int)call_info.remote_info.slen, 
-	    call_info.remote_info.ptr));
-
-    } else {
-	PJ_LOG(3,(THIS_FILE,"No current dialog"));
-    }
-}
-
-static void ui_cycle_account()
-{
-    int i;
-    char buf[128];
-
-    if (!simple_input("Enter account ID to select", buf, sizeof(buf)))
-	return;
-
-    i = my_atoi(buf);
-    if (pjsua_acc_is_valid(i)) {
-	pjsua_acc_set_default(i);
-	PJ_LOG(3,(THIS_FILE, "Current account changed to %d", i));
-    } else {
-	PJ_LOG(3,(THIS_FILE, "Invalid account id %d", i));
-    }
-}
-
-static void ui_add_buddy()
-{
-    char buf[128];
-    pjsua_buddy_config buddy_cfg;
-    pjsua_buddy_id buddy_id;
-    pj_status_t status;
-
-    if (!simple_input("Enter buddy's URI:", buf, sizeof(buf)))
-	return;
-
-    if (pjsua_verify_url(buf) != PJ_SUCCESS) {
-	printf("Invalid URI '%s'\n", buf);
-	return;
-    }
-
-    pj_bzero(&buddy_cfg, sizeof(pjsua_buddy_config));
-
-    buddy_cfg.uri = pj_str(buf);
-    buddy_cfg.subscribe = PJ_TRUE;
-
-    status = pjsua_buddy_add(&buddy_cfg, &buddy_id);
-    if (status == PJ_SUCCESS) {
-	printf("New buddy '%s' added at index %d\n",
-	    buf, buddy_id+1);
-    }
-}
-
-static void ui_add_account(pjsua_transport_config *rtp_cfg)
-{
-    char id[80], registrar[80], realm[80], uname[80], passwd[30];
-    pjsua_acc_config acc_cfg;
-    pj_status_t status;
-
-    if (!simple_input("Your SIP URL:", id, sizeof(id)))
-	return;
-    if (!simple_input("URL of the registrar:", registrar, sizeof(registrar)))
-	return;
-    if (!simple_input("Auth Realm:", realm, sizeof(realm)))
-	return;
-    if (!simple_input("Auth Username:", uname, sizeof(uname)))
-	return;
-    if (!simple_input("Auth Password:", passwd, sizeof(passwd)))
-	return;
-
-    pjsua_acc_config_default(&acc_cfg);
-    acc_cfg.id = pj_str(id);
-    acc_cfg.reg_uri = pj_str(registrar);
-    acc_cfg.cred_count = 1;
-    acc_cfg.cred_info[0].scheme = pj_str("Digest");
-    acc_cfg.cred_info[0].realm = pj_str(realm);
-    acc_cfg.cred_info[0].username = pj_str(uname);
-    acc_cfg.cred_info[0].data_type = 0;
-    acc_cfg.cred_info[0].data = pj_str(passwd);
-
-    acc_cfg.rtp_cfg = *rtp_cfg;    
-    app_config_init_video(&acc_cfg);
-
-    status = pjsua_acc_add(&acc_cfg, PJ_TRUE, NULL);
-    if (status != PJ_SUCCESS) {
-	pjsua_perror(THIS_FILE, "Error adding new account", status);
-    }
-}
-
-static void ui_delete_buddy()
-{
-    char buf[128];
-    int i;
-
-    if (!simple_input("Enter buddy ID to delete", buf, sizeof(buf)))
-	return;
-
-    i = my_atoi(buf) - 1;
-
-    if (!pjsua_buddy_is_valid(i)) {
-	printf("Invalid buddy id %d\n", i);
-    } else {
-	pjsua_buddy_del(i);
-	printf("Buddy %d deleted\n", i);
-    }
-}
-
-static void ui_delete_account()
-{
-    char buf[128];
-    int i;
-
-    if (!simple_input("Enter account ID to delete", buf, sizeof(buf)))
-	return;
-
-    i = my_atoi(buf);
-
-    if (!pjsua_acc_is_valid(i)) {
-	printf("Invalid account id %d\n", i);
-    } else {
-	pjsua_acc_del(i);
-	printf("Account %d deleted\n", i);
-    }
-}
-
-static void ui_call_hold()
-{
-    if (current_call != -1) {		
-	pjsua_call_set_hold(current_call, NULL);
-    } else {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    }
-}
-
-static void ui_call_reinvite()
-{
-    call_opt.flag |= PJSUA_CALL_UNHOLD;
-    pjsua_call_reinvite2(current_call, &call_opt, NULL);
-}
-
-static void ui_send_update()
-{
-    if (current_call != -1) {
-	call_opt.flag |= PJSUA_CALL_UNHOLD;
-	pjsua_call_update2(current_call, &call_opt, NULL);
-    } else {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    }
-}
-
-/*
- * Change codec priorities.
- */
-static void ui_manage_codec_prio()
-{
-    pjsua_codec_info c[32];
-    unsigned i, count = PJ_ARRAY_SIZE(c);
-    char input[32];
-    char *codec, *prio;
-    pj_str_t id;
-    int new_prio;
-    pj_status_t status;
-
-    printf("List of audio codecs:\n");
-    pjsua_enum_codecs(c, &count);
-    for (i=0; i<count; ++i) {
-	printf("  %d\t%.*s\n", c[i].priority, (int)c[i].codec_id.slen,
-			       c[i].codec_id.ptr);
-    }
-
-#if PJSUA_HAS_VIDEO
-    puts("");
-    printf("List of video codecs:\n");
-    pjsua_vid_enum_codecs(c, &count);
-    for (i=0; i<count; ++i) {
-	printf("  %d\t%.*s%s%.*s\n", c[i].priority,
-				     (int)c[i].codec_id.slen,
-				     c[i].codec_id.ptr,
-				     c[i].desc.slen? " - ":"",
-				     (int)c[i].desc.slen,
-				     c[i].desc.ptr);
-    }
-#endif
-
-    puts("");
-    puts("Enter codec id and its new priority (e.g. \"speex/16000 200\", "
-	 """\"H263 200\"),");
-    puts("or empty to cancel.");
-
-    printf("Codec name (\"*\" for all) and priority: ");
-    if (fgets(input, sizeof(input), stdin) == NULL)
-	return;
-    if (input[0]=='\r' || input[0]=='\n') {
-	puts("Done");
-	return;
-    }
-
-    codec = strtok(input, " \t\r\n");
-    prio = strtok(NULL, " \r\n");
-
-    if (!codec || !prio) {
-	puts("Invalid input");
-	return;
-    }
-
-    new_prio = atoi(prio);
-    if (new_prio < 0) 
-	new_prio = 0;
-    else if (new_prio > PJMEDIA_CODEC_PRIO_HIGHEST) 
-	new_prio = PJMEDIA_CODEC_PRIO_HIGHEST;
-
-    status = pjsua_codec_set_priority(pj_cstr(&id, codec), 
-				      (pj_uint8_t)new_prio);
-#if PJSUA_HAS_VIDEO
-    if (status != PJ_SUCCESS) {
-	status = pjsua_vid_codec_set_priority(pj_cstr(&id, codec), 
-					      (pj_uint8_t)new_prio);
-    }
-#endif
-    if (status != PJ_SUCCESS)
-	pjsua_perror(THIS_FILE, "Error setting codec priority", status);
-}
-
-static void ui_call_transfer(pj_bool_t no_refersub)
-{
-    if (current_call == -1) {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    } else {
-	int call = current_call;
-	char buf[128];
-	pjsip_generic_string_hdr refer_sub;
-	pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 };
-	pj_str_t STR_FALSE = { "false", 5 };
-	pjsua_call_info ci;
-	input_result result;
-	pjsua_msg_data msg_data;
-
-	pjsua_call_get_info(current_call, &ci);
-	printf("Transfering current call [%d] %.*s\n", current_call,
-	       (int)ci.remote_info.slen, ci.remote_info.ptr);
-
-	ui_input_url("Transfer to URL", buf, sizeof(buf), &result);
-
-	/* Check if call is still there. */
-
-	if (call != current_call) {
-	    puts("Call has been disconnected");
-	    return;
-	}
-
-	pjsua_msg_data_init(&msg_data);
-	if (no_refersub) {
-	    /* Add Refer-Sub: false in outgoing REFER request */
-	    pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB,
-		&STR_FALSE);
-	    pj_list_push_back(&msg_data.hdr_list, &refer_sub);
-	}
-	if (result.nb_result != NO_NB) {
-	    if (result.nb_result == -1 || result.nb_result == 0)
-		puts("You can't do that with transfer call!");
-	    else {
-		pjsua_buddy_info binfo;
-		pjsua_buddy_get_info(result.nb_result-1, &binfo);
-		pjsua_call_xfer( current_call, &binfo.uri, &msg_data);
-	    }
-
-	} else if (result.uri_result) {
-	    pj_str_t tmp;
-	    tmp = pj_str(result.uri_result);
-	    pjsua_call_xfer( current_call, &tmp, &msg_data);
-	}
-    }
-}
-
-static void ui_call_transfer_replaces(pj_bool_t no_refersub)
-{        
-    if (current_call == -1) {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    } else {
-	int call = current_call;
-	int dst_call;
-	pjsip_generic_string_hdr refer_sub;
-	pj_str_t STR_REFER_SUB = { "Refer-Sub", 9 };
-	pj_str_t STR_FALSE = { "false", 5 };
-	pjsua_call_id ids[PJSUA_MAX_CALLS];
-	pjsua_call_info ci;
-	pjsua_msg_data msg_data;
-	char buf[128];
-	unsigned i, count;
-
-	count = PJ_ARRAY_SIZE(ids);
-	pjsua_enum_calls(ids, &count);
-
-	if (count <= 1) {
-	    puts("There are no other calls");
-	    return;
-	}
-
-	pjsua_call_get_info(current_call, &ci);
-	printf("Transfer call [%d] %.*s to one of the following:\n",
-	       current_call,
-	       (int)ci.remote_info.slen, ci.remote_info.ptr);
-
-	for (i=0; i<count; ++i) {
-	    pjsua_call_info call_info;
-
-	    if (ids[i] == call)
-		return;
-
-	    pjsua_call_get_info(ids[i], &call_info);
-	    printf("%d  %.*s [%.*s]\n",
-		ids[i],
-		(int)call_info.remote_info.slen,
-		call_info.remote_info.ptr,
-		(int)call_info.state_text.slen,
-		call_info.state_text.ptr);
-	}
-
-	if (!simple_input("Enter call number to be replaced", buf, sizeof(buf)))
-	    return;
-
-	dst_call = my_atoi(buf);
-
-	/* Check if call is still there. */
-
-	if (call != current_call) {
-	    puts("Call has been disconnected");
-	    return;
-	}
-
-	/* Check that destination call is valid. */
-	if (dst_call == call) {
-	    puts("Destination call number must not be the same "
-		"as the call being transfered");
-	    return;
-	}
-	if (dst_call >= PJSUA_MAX_CALLS) {
-	    puts("Invalid destination call number");
-	    return;
-	}
-	if (!pjsua_call_is_active(dst_call)) {
-	    puts("Invalid destination call number");
-	    return;
-	}
-
-	pjsua_msg_data_init(&msg_data);
-	if (no_refersub) {
-	    /* Add Refer-Sub: false in outgoing REFER request */
-	    pjsip_generic_string_hdr_init2(&refer_sub, &STR_REFER_SUB, 
-					   &STR_FALSE);
-	    pj_list_push_back(&msg_data.hdr_list, &refer_sub);
-	}
-
-	pjsua_call_xfer_replaces(call, dst_call, 
-				 PJSUA_XFER_NO_REQUIRE_REPLACES, 
-				 &msg_data);
-    }
-}
-
-static void ui_send_dtmf_2833()
-{
-    if (current_call == -1) {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    } else if (!pjsua_call_has_media(current_call)) {
-	PJ_LOG(3,(THIS_FILE, "Media is not established yet!"));
-    } else {
-	pj_str_t digits;
-	int call = current_call;
-	pj_status_t status;
-	char buf[128];
-
-	if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, 
-	    sizeof(buf)))
-	{
-	    return;
-	}
-
-	if (call != current_call) {
-	    puts("Call has been disconnected");
-	    return;
-	}
-
-	digits = pj_str(buf);
-	status = pjsua_call_dial_dtmf(current_call, &digits);
-	if (status != PJ_SUCCESS) {
-	    pjsua_perror(THIS_FILE, "Unable to send DTMF", status);
-	} else {
-	    puts("DTMF digits enqueued for transmission");
-	}
-    }
-}
-
-static void ui_send_dtmf_info()
-{
-    if (current_call == -1) {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    } else {
-	const pj_str_t SIP_INFO = pj_str("INFO");
-	pj_str_t digits;
-	int call = current_call;
-	int i;
-	pj_status_t status;
-	char buf[128];
-
-	if (!simple_input("DTMF strings to send (0-9*#A-B)", buf, 
-	    sizeof(buf)))
-	{
-	    return;
-	}
-
-	if (call != current_call) {
-	    puts("Call has been disconnected");
-	    return;
-	}
-
-	digits = pj_str(buf);
-	for (i=0; i<digits.slen; ++i) {
-	    char body[80];
-	    pjsua_msg_data msg_data;
-
-	    pjsua_msg_data_init(&msg_data);
-	    msg_data.content_type = pj_str("application/dtmf-relay");
-
-	    pj_ansi_snprintf(body, sizeof(body),
-		"Signal=%c\r\n"
-		"Duration=160",
-		buf[i]);
-	    msg_data.msg_body = pj_str(body);
-
-	    status = pjsua_call_send_request(current_call, &SIP_INFO, 
-		&msg_data);
-	    if (status != PJ_SUCCESS) {
-		return;
-	    }
-	}
-    }
-}
-
-static void ui_send_arbitrary_request()
-{
-    char text[128];
-    char buf[128];
-    char *uri;
-    input_result result;
-    pj_str_t tmp;
-
-    if (pjsua_acc_get_count() == 0) {
-	puts("Sorry, need at least one account configured");
-	return;
-    }
-
-    puts("Send arbitrary request to remote host");
-
-    /* Input METHOD */
-    if (!simple_input("Request method:",text,sizeof(text)))
-	return;
-
-    /* Input destination URI */
-    uri = NULL;
-    ui_input_url("Destination URI", buf, sizeof(buf), &result);
-    if (result.nb_result != NO_NB) {
-
-	if (result.nb_result == -1) {
-	    puts("Sorry you can't do that!");
-	    return;
-	} else if (result.nb_result == 0) {
-	    uri = NULL;
-	    if (current_call == PJSUA_INVALID_ID) {
-		puts("No current call");
-		return;
-	    }
-	} else {	    
-	    pjsua_buddy_info binfo;
-	    pjsua_buddy_get_info(result.nb_result-1, &binfo);
-	    tmp.ptr = buf;
-	    pj_strncpy_with_null(&tmp, &binfo.uri, sizeof(buf));
-	    uri = buf;
-	}
-
-    } else if (result.uri_result) {
-	uri = result.uri_result;
-    } else {
-	return;
-    }
-
-    if (uri) {
-	tmp = pj_str(uri);
-	send_request(text, &tmp);
-    } else {
-	/* If you send call control request using this method
-	* (such requests includes BYE, CANCEL, etc.), it will
-	* not go well with the call state, so don't do it
-	* unless it's for testing.
-	*/
-	pj_str_t method = pj_str(text);
-	pjsua_call_send_request(current_call, &method, NULL);
-    }	    
-}
-
-static void ui_echo(char menuin[])
-{
-    if (pj_ansi_strnicmp(menuin, "echo", 4)==0) {
-	pj_str_t tmp;
-
-	tmp.ptr = menuin+5;
-	tmp.slen = pj_ansi_strlen(menuin)-6;
-
-	if (tmp.slen < 1) {
-	    puts("Usage: echo [0|1]");
-	    return;
-	}
-	cmd_echo = *tmp.ptr != '0' || tmp.slen!=1;
-    }
-}
-
-static void ui_sleep(char menuin[])
-{
-    if (pj_ansi_strnicmp(menuin, "sleep", 5)==0) {
-	pj_str_t tmp;
-	int delay;
-
-	tmp.ptr = menuin+6;
-	tmp.slen = pj_ansi_strlen(menuin)-7;
-
-	if (tmp.slen < 1) {
-	    puts("Usage: sleep MSEC");
-	    return;
-	}
-
-	delay = pj_strtoul(&tmp);
-	if (delay < 0) delay = 0;
-	pj_thread_sleep(delay);		
-    }
-}
-
-static void ui_subscribe(char menuin[])
-{
-    char buf[128];
-    input_result result;
-
-    ui_input_url("(un)Subscribe presence of", buf, sizeof(buf), &result);
-    if (result.nb_result != NO_NB) {
-	if (result.nb_result == -1) {
-	    int i, count;
-	    count = pjsua_get_buddy_count();
-	    for (i=0; i<count; ++i)
-		pjsua_buddy_subscribe_pres(i, menuin[0]=='s');
-	} else if (result.nb_result == 0) {
-	    puts("Sorry, can only subscribe to buddy's presence, "
-		"not from existing call");
-	} else {
-	    pjsua_buddy_subscribe_pres(result.nb_result-1, (menuin[0]=='s'));
-	}
-
-    } else if (result.uri_result) {
-	puts("Sorry, can only subscribe to buddy's presence, "
-	    "not arbitrary URL (for now)");
-    }
-}
-
-static void ui_register(char menuin[])
-{
-    switch (menuin[1]) {
-    case 'r':
-	/*
-	* Re-Register.
-	*/
-	pjsua_acc_set_registration(current_acc, PJ_TRUE);
-	break;
-    case 'u':
-	/*
-	* Unregister
-	*/
-	pjsua_acc_set_registration(current_acc, PJ_FALSE);
-	break;
-    }
-}
-
-static void ui_toggle_state()
-{
-    pjsua_acc_info acc_info;
-
-    pjsua_acc_get_info(current_acc, &acc_info);
-    acc_info.online_status = !acc_info.online_status;
-    pjsua_acc_set_online_status(current_acc, acc_info.online_status);
-    printf("Setting %s online status to %s\n",
-	   acc_info.acc_uri.ptr,
-	   (acc_info.online_status?"online":"offline"));
-}
-
-/*
- * Change extended online status.
- */
-static void ui_change_online_status()
-{
-    char menuin[32];
-    pj_bool_t online_status;
-    pjrpid_element elem;
-    int i, choice;
-
-    enum {
-	AVAILABLE, BUSY, OTP, IDLE, AWAY, BRB, OFFLINE, OPT_MAX
-    };
-
-    struct opt {
-	int id;
-	char *name;
-    } opts[] = {
-	{ AVAILABLE, "Available" },
-	{ BUSY, "Busy"},
-	{ OTP, "On the phone"},
-	{ IDLE, "Idle"},
-	{ AWAY, "Away"},
-	{ BRB, "Be right back"},
-	{ OFFLINE, "Offline"}
-    };
-
-    printf("\n"
-	   "Choices:\n");
-    for (i=0; i<PJ_ARRAY_SIZE(opts); ++i) {
-	printf("  %d  %s\n", opts[i].id+1, opts[i].name);
-    }
-
-    if (!simple_input("Select status", menuin, sizeof(menuin)))
-	return;
-
-    choice = atoi(menuin) - 1;
-    if (choice < 0 || choice >= OPT_MAX) {
-	puts("Invalid selection");
-	return;
-    }
-
-    pj_bzero(&elem, sizeof(elem));
-    elem.type = PJRPID_ELEMENT_TYPE_PERSON;
-
-    online_status = PJ_TRUE;
-
-    switch (choice) {
-    case AVAILABLE:
-	break;
-    case BUSY:
-	elem.activity = PJRPID_ACTIVITY_BUSY;
-	elem.note = pj_str("Busy");
-	break;
-    case OTP:
-	elem.activity = PJRPID_ACTIVITY_BUSY;
-	elem.note = pj_str("On the phone");
-	break;
-    case IDLE:
-	elem.activity = PJRPID_ACTIVITY_UNKNOWN;
-	elem.note = pj_str("Idle");
-	break;
-    case AWAY:
-	elem.activity = PJRPID_ACTIVITY_AWAY;
-	elem.note = pj_str("Away");
-	break;
-    case BRB:
-	elem.activity = PJRPID_ACTIVITY_UNKNOWN;
-	elem.note = pj_str("Be right back");
-	break;
-    case OFFLINE:
-	online_status = PJ_FALSE;
-	break;
-    }
-
-    pjsua_acc_set_online_status2(current_acc, online_status, &elem);
-}
-
-/*
- * List the ports in conference bridge
- */
-static void ui_conf_list()
-{
-    unsigned i, count;
-    pjsua_conf_port_id id[PJSUA_MAX_CALLS];
-
-    printf("Conference ports:\n");
-
-    count = PJ_ARRAY_SIZE(id);
-    pjsua_enum_conf_ports(id, &count);
-
-    for (i=0; i<count; ++i) {
-	char txlist[PJSUA_MAX_CALLS*4+10];
-	unsigned j;
-	pjsua_conf_port_info info;
-
-	pjsua_conf_get_port_info(id[i], &info);
-
-	txlist[0] = '\0';
-	for (j=0; j<info.listener_cnt; ++j) {
-	    char s[10];
-	    pj_ansi_snprintf(s, sizeof(s), "#%d ", info.listeners[j]);
-	    pj_ansi_strcat(txlist, s);
-	}
-	printf("Port #%02d[%2dKHz/%dms/%d] %20.*s  transmitting to: %s\n", 
-	       info.slot_id, 
-	       info.clock_rate/1000,
-	       info.samples_per_frame*1000/info.channel_count/info.clock_rate,
-	       info.channel_count,
-	       (int)info.name.slen, 
-	       info.name.ptr,
-	       txlist);
-
-    }
-    puts("");
-}
-
-static void ui_conf_connect(char menuin[])
-{
-    char tmp[10], src_port[10], dst_port[10];
-    pj_status_t status;
-    int cnt;
-    const char *src_title, *dst_title;
-
-    cnt = sscanf(menuin, "%s %s %s", tmp, src_port, dst_port);
-
-    if (cnt != 3) {
-	ui_conf_list();
-
-	src_title = (menuin[1]=='c'? "Connect src port #":
-				     "Disconnect src port #");
-	dst_title = (menuin[1]=='c'? "To dst port #":"From dst port #");
-
-	if (!simple_input(src_title, src_port, sizeof(src_port)))
-	    return;
-
-	if (!simple_input(dst_title, dst_port, sizeof(dst_port)))
-	    return;
-    }
-
-    if (menuin[1]=='c') {
-	status = pjsua_conf_connect(my_atoi(src_port), my_atoi(dst_port));
-    } else {
-	status = pjsua_conf_disconnect(my_atoi(src_port), my_atoi(dst_port));
-    }
-    if (status == PJ_SUCCESS) {
-	puts("Success");
-    } else {
-	puts("ERROR!!");
-    }
-}
-
-static void ui_adjust_volume()
-{
-    char buf[128];
-    char text[128];
-    sprintf(buf, "Adjust mic level: [%4.1fx] ", app_config.mic_level);
-    if (simple_input(buf,text,sizeof(text))) {
-	char *err;
-	app_config.mic_level = (float)strtod(text, &err);
-	pjsua_conf_adjust_rx_level(0, app_config.mic_level);
-    }
-    sprintf(buf, "Adjust speaker level: [%4.1fx] ", app_config.speaker_level);
-    if (simple_input(buf,text,sizeof(text))) {
-	char *err;
-	app_config.speaker_level = (float)strtod(text, &err);
-	pjsua_conf_adjust_tx_level(0, app_config.speaker_level);
-    }
-}
-
-static void ui_dump_call_quality()
-{
-    if (current_call != PJSUA_INVALID_ID) {
-	log_call_dump(current_call);
-    } else {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    }
-}
-
-static void ui_dump_configuration()
-{
-    char settings[2000];
-    int len;
-
-    len = write_settings(&app_config, settings, sizeof(settings));
-    if (len < 1)
-	PJ_LOG(1,(THIS_FILE, "Error: not enough buffer"));
-    else
-	PJ_LOG(3,(THIS_FILE, "Dumping configuration (%d bytes):\n%s\n",	
-		  len, settings));	
-}
-
-static void ui_write_settings()
-{
-    char settings[2000];
-    int len;
-    char buf[128];
-
-    len = write_settings(&app_config, settings, sizeof(settings));
-    if (len < 1)
-	PJ_LOG(1,(THIS_FILE, "Error: not enough buffer"));
-    else {
-	pj_oshandle_t fd;
-	pj_status_t status;
-
-	status = pj_file_open(app_config.pool, buf, PJ_O_WRONLY, &fd);
-	if (status != PJ_SUCCESS) {
-	    pjsua_perror(THIS_FILE, "Unable to open file", status);
-	} else {
-	    pj_ssize_t size = len;
-	    pj_file_write(fd, settings, &size);
-	    pj_file_close(fd);
-
-	    printf("Settings successfully written to '%s'\n", buf);
-	}
-    }
-}
-
-/*
- * Dump application states.
- */
-static void ui_app_dump(pj_bool_t detail)
-{
-    pjsua_dump(detail);
-}
-
-static void ui_call_redirect(char menuin[])
-{
-    if (current_call == PJSUA_INVALID_ID) {
-	PJ_LOG(3,(THIS_FILE, "No current call"));
-    } else {
-	if (!pjsua_call_is_active(current_call)) {
-	    PJ_LOG(1,(THIS_FILE, "Call %d has gone", current_call));
-	} else if (menuin[1] == 'a') {
-	    pjsua_call_process_redirect(current_call, 
-		PJSIP_REDIRECT_ACCEPT_REPLACE);
-	} else if (menuin[1] == 'A') {
-	    pjsua_call_process_redirect(current_call, 
-		PJSIP_REDIRECT_ACCEPT);
-	} else if (menuin[1] == 'r') {
-	    pjsua_call_process_redirect(current_call,
-		PJSIP_REDIRECT_REJECT);
-	} else {
-	    pjsua_call_process_redirect(current_call,
-		PJSIP_REDIRECT_STOP);
-	}
-    }
-}
-
-/*
- * Main "user interface" loop.
- */
-void console_app_main(const pj_str_t *uri_to_call, pj_bool_t *app_restart)
-{    
-    char menuin[80];    
-    char buf[128];    
-
-    pjsua_call_setting_default(&call_opt);
-    call_opt.aud_cnt = app_config.aud_cnt;
-    call_opt.vid_cnt = app_config.vid.vid_cnt;
-
-    /* If user specifies URI to call, then call the URI */
-    if (uri_to_call->slen) {
-	pjsua_call_make_call( current_acc, uri_to_call, &call_opt, 
-			      NULL, NULL, NULL);
-    }
-
-    keystroke_help(current_call);
-
-    for (;;) {
-
-	printf(">>> ");
-	fflush(stdout);
-
-	if (fgets(menuin, sizeof(menuin), stdin) == NULL) {
-	    /* 
-	     * Be friendly to users who redirect commands into
-	     * program, when file ends, resume with kbd.
-	     * If exit is desired end script with q for quit
-	     */
- 	    /* Reopen stdin/stdout/stderr to /dev/console */
-#if defined(PJ_WIN32) && PJ_WIN32!=0
-	    if (freopen ("CONIN$", "r", stdin) == NULL) {
-#else
-	    if (1) {
-#endif
-		puts("Cannot switch back to console from file redirection");
-		menuin[0] = 'q';
-		menuin[1] = '\0';
-	    } else {
-		puts("Switched back to console from file redirection");
-		continue;
-	    }
-	}
-
-	if (cmd_echo) {
-	    printf("%s", menuin);
-	}
-
-	/* Update call setting */
-	pjsua_call_setting_default(&call_opt);
-	call_opt.aud_cnt = app_config.aud_cnt;
-	call_opt.vid_cnt = app_config.vid.vid_cnt;
-
-	switch (menuin[0]) {
-
-	case 'm':
-	    /* Make call! : */
-	    ui_make_new_call();
-	    break;
-
-	case 'M':
-	    /* Make multiple calls! : */
-	    ui_make_multi_call();
-	    break;
-
-	case 'n':
-	    ui_detect_nat_type();
-	    break;
-
-	case 'i':
-	    /* Send instant messaeg */
-	    ui_send_instant_message();
-	    break;
-
-	case 'a':
-	    ui_answer_call();
-	    break;
-
-	case 'h':
-	    ui_hangup_call(menuin);
-	    break;
-
-	case ']':
-	case '[':
-	    /*
-	     * Cycle next/prev dialog.
-	     */
-	    ui_cycle_dialog(menuin);
-	    break;
-
-	case '>':
-	case '<':
-	    ui_cycle_account();
-	    break;
-
-	case '+':
-	    if (menuin[1] == 'b') {
-		ui_add_buddy();
-	    } else if (menuin[1] == 'a') {
-		ui_add_account(&app_config.rtp_cfg);
-	    } else {
-		printf("Invalid input %s\n", menuin);
-	    }
-	    break;
-
-	case '-':
-	    if (menuin[1] == 'b') {
-		ui_delete_buddy();
-	    } else if (menuin[1] == 'a') {
-		ui_delete_account();
-	    } else {
-		printf("Invalid input %s\n", menuin);
-	    }
-	    break;
-
-	case 'H':
-	    /*
-	     * Hold call.
-	     */
-	    ui_call_hold();
-	    break;
-
-	case 'v':	    
-#if PJSUA_HAS_VIDEO
-	    if (menuin[1]=='i' && menuin[2]=='d' && menuin[3]==' ') {
-		vid_handle_menu(menuin);
-	    } else
-#endif
-	    if (current_call != -1) {
-		/*
-		 * re-INVITE
-		 */
-		ui_call_reinvite();
-	    } else {
-		PJ_LOG(3,(THIS_FILE, "No current call"));
-	    }
-	    break;
-
-	case 'U':
-	    /*
-	     * Send UPDATE
-	     */
-	    ui_send_update();
-	    break;
-
-	case 'C':
-	    if (menuin[1] == 'p') {
-		ui_manage_codec_prio();
-	    }
-	    break;
-
-	case 'x':
-	    /*
-	     * Transfer call.
-	     */
-	    ui_call_transfer(app_config.no_refersub);
-	    break;
-
-	case 'X':
-	    /*
-	     * Transfer call with replaces.
-	     */
-	    ui_call_transfer_replaces(app_config.no_refersub);
-	    break;
-
-	case '#':
-	    /*
-	     * Send DTMF strings.
-	     */
-	    ui_send_dtmf_2833();
-	    break;
-
-	case '*':
-	    /* Send DTMF with INFO */
-	    ui_send_dtmf_info();
-	    break;
-
-	case 'S':
-	    /*
-	     * Send arbitrary request
-	     */
-	    ui_send_arbitrary_request();
-	    break;
-
-	case 'e':
-	    ui_echo(menuin);
-	    break;
-
-	case 's':	    
-	    ui_sleep(menuin);
-	    break;
-	    /* Continue below */
-
-	case 'u':
-	    /*
-	     * Subscribe/unsubscribe presence.
-	     */
-	    ui_subscribe(menuin);
-	    break;
-
-	case 'r':
-	    ui_register(menuin);
-	    break;
-	    
-	case 't':
-	    ui_toggle_state();
-	    break;
-
-	case 'T':
-	    ui_change_online_status();
-	    break;
-
-	case 'c':
-	    switch (menuin[1]) {
-	    case 'l':
-		ui_conf_list();
-		break;
-	    case 'c':
-	    case 'd':
-		ui_conf_connect(menuin);
-		break;
-	    }
-	    break;
-
-	case 'V':
-	    /* Adjust audio volume */	    
-	    ui_adjust_volume();
-	    break;
-
-	case 'd':
-	    if (menuin[1] == 'c') {
-		ui_dump_configuration();	
-	    } else if (menuin[1] == 'q') {
-		ui_dump_call_quality();
-	    } else {		
-		ui_app_dump(menuin[1]=='d');
-	    }
-	    break;
-
-	case 'f':
-	    if (simple_input("Enter output filename", buf, sizeof(buf))) {
-		ui_write_settings();		
-	    }
-	    break;
-
-	case 'L':   /* Restart */
-	    *app_restart = PJ_TRUE;
-	    /* Continues below */
-
-	case 'q':
-	    goto on_exit;
-
-	case 'R':	    
-	    ui_call_redirect(menuin);
-	    break;
-
-	default:
-	    if (menuin[0] != '\n' && menuin[0] != '\r') {
-		printf("Invalid input %s", menuin);
-	    }
-	    keystroke_help();
-	    break;
-	}
-    }
-
-on_exit:
-    ;
-} 
-
