changeset 391:a2b7ac328e62 dev-0_9_12

Code cleanup.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 24 May 2012 00:55:45 +0300
parents acea18a741e3
children a21cc444d800
files nnchat.c
diffstat 1 files changed, 740 insertions(+), 523 deletions(-) [+]
line wrap: on
line diff
--- a/nnchat.c	Thu May 24 00:47:31 2012 +0300
+++ b/nnchat.c	Thu May 24 00:55:45 2012 +0300
@@ -75,7 +75,8 @@
 
 /* Logging mode flags
  */
-enum {
+enum
+{
     LOG_FILE   = 1,
     LOG_WINDOW = 2,
     LOG_STAMP  = 4
@@ -84,7 +85,8 @@
 
 /* Arguments
  */
-optarg_t optList[] = {
+optarg_t optList[] =
+{
     { 0, '?', "help",       "Show this help", OPT_NONE },
     { 1, 'v', "verbose",    "Be more verbose", OPT_NONE },
     { 2, 'p', "port",       "Connect to port", OPT_ARGREQ },
@@ -94,7 +96,7 @@
     { 6, 'D', "daemon",     "A pseudo-daemon mode for logging", OPT_NONE },
     { 7, 'f', "force-site", "Force site (default: NN)", OPT_ARGREQ },
     { 8, 'd', "debug",      "Enable various debug features", OPT_NONE },
-    
+
     {10, '4', "socks4",     "SOCKS4 proxy server", OPT_ARGREQ },
     {11, 'A', "socks4a",    "SOCKS4A proxy server", OPT_ARGREQ },
     {12, 'P', "proxy-port", "Proxy port (default: 1080)", OPT_ARGREQ },
@@ -106,15 +108,16 @@
 void argShowHelp(void)
 {
     th_print_banner(stdout, th_prog_name,
-        "[options] <username> <password>");
-    
+                    "[options] <username> <password>");
+
     th_args_help(stdout, optList, optListN);
 }
 
 
 BOOL argHandleOpt(const int optN, char *optArg, char *currArg)
 {
-    switch (optN) {
+    switch (optN)
+    {
     case 0:
         argShowHelp();
         exit(0);
@@ -123,7 +126,7 @@
     case 1:
         th_verbosityLevel++;
         break;
-    
+
     case 2:
         optPort = atoi(optArg);
         break;
@@ -131,9 +134,10 @@
     case 3:
         optServer = optArg;
         break;
-    
+
     case 4:
-        if ((optUserColor = th_get_hex_triplet(optArg)) < 0) {
+        if ((optUserColor = th_get_hex_triplet(optArg)) < 0)
+        {
             THERR("Invalid color argument '%s', should be a RGB hex triplet '000000'.\n",
                 optArg);
             return FALSE;
@@ -180,7 +184,7 @@
         THERR("Unknown option '%s'.\n", currArg);
         return FALSE;
     }
-    
+
     return TRUE;
 }
 
@@ -191,11 +195,12 @@
         optUserNameCmd = currArg;
     else if (!optPasswordCmd)
         optPasswordCmd = currArg;
-    else {
+    else
+    {
         THERR("Username '%s' already specified on commandline!\n", optUserNameCmd);
         return FALSE;
     }
-    
+
     return TRUE;
 }
 
@@ -203,10 +208,13 @@
 {
     time_t stamp = time(NULL);
     struct tm *stamp_tm;
-    if ((stamp_tm = localtime(&stamp)) != NULL) {
+    if ((stamp_tm = localtime(&stamp)) != NULL)
+    {
         strftime(str, len, fmt, stamp_tm);
         return TRUE;
-    } else {
+    }
+    else
+    {
         str[0] = 0;
         return FALSE;
     }
@@ -238,14 +246,15 @@
         return FALSE;
 
     for (i = 1; i < SET_MAX_WINDOWS; i++)
-    if (chatWindows[i] == NULL) {
-        res->num = i;
-        chatWindows[i] = res;
-        if (curwin)
-            currWin = res;
-        return TRUE;
-    }
-    
+        if (chatWindows[i] == NULL)
+        {
+            res->num = i;
+            chatWindows[i] = res;
+            if (curwin)
+                currWin = res;
+            return TRUE;
+        }
+
     return FALSE;
 }
 
@@ -256,11 +265,12 @@
     if (win == NULL) return;
 
     for (i = 1; i < SET_MAX_WINDOWS; i++)
-    if (chatWindows[i] == win) {
-        chatWindows[i] = NULL;
-        nn_window_free(win);
-        return;
-    }
+        if (chatWindows[i] == win)
+        {
+            chatWindows[i] = NULL;
+            nn_window_free(win);
+            return;
+        }
 }
 
 
@@ -268,17 +278,17 @@
 {
     char tmpStr[128];
     int i;
-    
+
     if (statusWin == NULL) return;
-    
+
     getTimeStamp(tmpStr, sizeof(tmpStr), "%H:%M:%S");
 
     wbkgdset(statusWin, COLOR_PAIR(10));
     werase(statusWin);
-    
+
     wattrset(statusWin, A_BOLD | COLOR_PAIR(11));
     mvwaddstr(statusWin, 0, 1, tmpStr);
-    
+
     wattrset(statusWin, A_BOLD | COLOR_PAIR(13));
     waddstr(statusWin, " | ");
     wattrset(statusWin, A_BOLD | COLOR_PAIR(16));
@@ -304,10 +314,11 @@
     wattrset(statusWin, A_BOLD | COLOR_PAIR(11));
 
     for (i = 0; i < SET_MAX_WINDOWS; i++)
-    if (chatWindows[i] != NULL && chatWindows[i]->dirty) {
-        snprintf(tmpStr, sizeof(tmpStr), "%d ", i + 1);
-        waddstr(statusWin, tmpStr);
-    }
+        if (chatWindows[i] != NULL && chatWindows[i]->dirty)
+        {
+            snprintf(tmpStr, sizeof(tmpStr), "%d ", i + 1);
+            waddstr(statusWin, tmpStr);
+        }
 
     wrefresh(statusWin);
 }
@@ -320,18 +331,21 @@
 
     buf->data[buf->len] = 0;
     tmp = nn_username_decode(th_strdup(buf->data));
-    
+
     werase(editWin);
-    
+
     wattrset(editWin, A_NORMAL);
-    
-    if (buf->pos < buf->len) {
+
+    if (buf->pos < buf->len)
+    {
         waddnstr(editWin, tmp, buf->pos);
         wattrset(editWin, A_REVERSE);
         waddch(editWin, tmp[buf->pos]);
         wattrset(editWin, A_NORMAL);
         waddnstr(editWin, tmp + buf->pos + 1, buf->len - buf->pos - 1);
-    } else {
+    }
+    else
+    {
         waddnstr(editWin, tmp, buf->len);
         wattrset(editWin, A_REVERSE);
         waddch(editWin, ' ');
@@ -347,17 +361,24 @@
     const char *s = fmt;
     int col = 0;
 
-    while (*s) {
-        if (*s == '½') {
+    while (*s)
+    {
+        if (*s == '½')
+        {
             s++;
-            if (*s == '½') {
+            if (*s == '½')
+            {
                 waddch(win, ((unsigned char) *s) | col);
                 s++;
-            } else {
+            }
+            else
+            {
                 memcpy(&col, s, sizeof(int));
                 s += sizeof(int);
             }
-        } else {
+        }
+        else
+        {
             waddch(win, ((unsigned char) *s) | col);
             s++;
         }
@@ -372,16 +393,22 @@
 {
     const char *s = fmt;
     int col = 0;
-    while (*s) {
-        if (*s == '½') {
+    while (*s)
+    {
+        if (*s == '½')
+        {
             s++;
-            if (*s == '½') {
+            if (*s == '½')
+            {
                 QPUTCH(*s);
                 QPUTCH(*s);
                 win->chlen++;
-            } else {
+            }
+            else
+            {
                 int val = 0;
-                while (*s >= '0' && *s <= '9') {
+                while (*s >= '0' && *s <= '9')
+                {
                     val *= 10;
                     val += (*s - '0');
                     s++;
@@ -397,12 +424,13 @@
 
                 if (!th_growbuf(&(win->buf), &(win->bufsize), &(win->len), sizeof(int)))
                     return -2;
- 
+
                 memcpy(win->buf + win->len, &col, sizeof(int));
                 win->len += sizeof(int);
             }
-        } else
-        if (*s == '\n') {
+        }
+        else if (*s == '\n')
+        {
             QPUTCH('\n');
             QPUTCH(0);
             th_ringbuf_add(win->data, win->buf);
@@ -410,8 +438,8 @@
             win->chlen = 0;
             win->dirty = TRUE;
         }
-        else    
-        if (*s != '\r') {
+        else if (*s != '\r')
+        {
             QPUTCH((unsigned char) *s == 255 ? ' ' : *s);
             win->chlen++;
         }
@@ -443,33 +471,41 @@
     /* Clear and redraw window */
     werase(mainWin);
     scrollok(mainWin, 1);
-    for (offs = buf->size - h - currWin->pos; offs >= 0 && offs < buf->size - currWin->pos && offs < buf->size; offs++) {
+    for (offs = buf->size - h - currWin->pos; offs >= 0 && offs < buf->size - currWin->pos && offs < buf->size; offs++)
+    {
         if (buf->data[offs] != NULL)
             printWin(mainWin, buf->data[offs]);
     }
-    
+
     currWin->dirty = FALSE;
     wrefresh(mainWin);
-    return TRUE; 
+    return TRUE;
 }
 
 
 int printFile(FILE *outFile, const char *fmt)
 {
     const char *s = fmt;
-    
-    while (*s) {
-        if (*s == '½') {
+
+    while (*s)
+    {
+        if (*s == '½')
+        {
             s++;
-            if (*s == '½') {
+            if (*s == '½')
+            {
                 fputc((unsigned char) *s, outFile);
                 s++;
-            } else {
+            }
+            else
+            {
                 while (*s && isdigit((int) *s)) s++;
                 if (*s != '½') return -1;
                 s++;
             }
-        } else {
+        }
+        else
+        {
             if ((unsigned char) *s == 255)
                 fputc(' ', outFile);
             else
@@ -477,37 +513,39 @@
             s++;
         }
     }
-    
+
     return 0;
 }
 
 void printMsgV(nn_window_t *win, int flags, const char *fmt, va_list ap)
 {
     char tmpStr[128], *buf;
-    
+
     getTimeStamp(tmpStr, sizeof(tmpStr), "½17½[½11½%H:%M:%S½17½]½0½ ");
-    
+
     buf = th_strdup_vprintf(fmt, ap);
-    
-    if (optLogFile && (flags & LOG_FILE)) {
+
+    if (optLogFile && (flags & LOG_FILE))
+    {
         if (flags & LOG_STAMP) printFile(optLogFile, tmpStr);
         printFile(optLogFile, buf);
         fflush(optLogFile);
     }
-    
-    if (!optDaemon && (flags & LOG_WINDOW)) {
+
+    if (!optDaemon && (flags & LOG_WINDOW))
+    {
         nn_window_t *tmp = win != NULL ? win : chatWindows[0];
         if (flags & LOG_STAMP) nn_window_print(tmp, tmpStr);
         nn_window_print(tmp, buf);
     }
-    
+
     th_free(buf);
 }
 
 void printMsg(nn_window_t *win, const char *fmt, ...)
 {
     va_list ap;
-    
+
     va_start(ap, fmt);
     printMsgV(win, LOG_STAMP | LOG_WINDOW | LOG_FILE, fmt, ap);
     va_end(ap);
@@ -516,7 +554,7 @@
 void printMsgF(nn_window_t *win, int flags, const char *fmt, ...)
 {
     va_list ap;
-    
+
     va_start(ap, fmt);
     printMsgV(win, flags | LOG_STAMP, fmt, ap);
     va_end(ap);
@@ -525,7 +563,7 @@
 void printMsgQ(nn_window_t *win, const char *fmt, ...)
 {
     va_list ap;
-    
+
     va_start(ap, fmt);
     printMsgV(win, LOG_STAMP | LOG_WINDOW, fmt, ap);
     va_end(ap);
@@ -539,13 +577,15 @@
     char *tmp = th_strdup_vprintf(fmt, ap);
 
     printMsg(NULL, "%s", tmp);
-    
-    if (errorMessages != NULL) {
+
+    if (errorMessages != NULL)
+    {
         char *tmp2 = th_strdup_printf("%s%s", errorMessages, tmp);
         th_free(errorMessages);
         th_free(tmp);
         errorMessages = tmp2;
-    } else
+    }
+    else
         errorMessages = tmp;
 }
 
@@ -574,7 +614,8 @@
 BOOL checkIgnoreList(const char *name)
 {
     qlist_t *node = setIgnoreList;
-    while (node != NULL) {
+    while (node != NULL)
+    {
         if (th_strcasecmp(name, (char *) node->data) == 0)
             return TRUE;
         node = node->next;
@@ -588,27 +629,28 @@
     const char *msg = "</USER><MESSAGE>", *p = str;
     BOOL isMine, isIgnored = FALSE;
     char *s, *t, *userName;
-    
+
     (void) conn;
-    
+
     /* Find start of the message */
     s = strstr(str, msg);
     if (!s) return 1;
     *s = 0;
     s += strlen(msg);
-    
+
     /* Find end of the message */
     t = strstr(s, "</MESSAGE>");
     if (!t) return 3;
     *t = 0;
-    
+
     /* Decode message string */
     s = nn_decode_str1(s);
     if (!s) return -1;
-    
+
     /* Decode username */
     userName = nn_decode_str1(p);
-    if (!userName) {
+    if (!userName)
+    {
         th_free(s);
         return -2;
     }
@@ -620,21 +662,26 @@
     isIgnored = setIgnoreMode && !isMine && checkIgnoreList(userName);
 
     /* Is it a special control message? */
-    if (*s == '/') {
+    if (*s == '/')
+    {
         /* Ignore room join/leave messages */
         if (!optDebug && (strstr(s, "left the room") || strstr(s, "joined the room from")))
             goto done;
 
         t = nn_strip_tags(s + 1);
-        if (!strncmp(t, "BPRV ", 5)) {
+        if (!strncmp(t, "BPRV ", 5))
+        {
             char *name, *tmp, *msg, *h;
             nn_window_t *win;
             h = nn_decode_str2(t + 1);
-            
-            if (!strncmp(t, "BPRV from ", 10)) {
+
+            if (!strncmp(t, "BPRV from ", 10))
+            {
                 name = nn_decode_str2(t + 10);
                 isMine = FALSE;
-            } else {
+            }
+            else
+            {
                 name = nn_decode_str2(t + 8);
                 isMine = TRUE;
             }
@@ -648,20 +695,25 @@
 
             isIgnored = setIgnoreMode && checkIgnoreList(name);
             win = findWindow(name);
-            
-            if (win != NULL) {
+
+            if (win != NULL)
+            {
                 printMsgF(win, isIgnored ? 0 : LOG_WINDOW,
                     "½5½<½%d½%s½5½>½0½ %s\n",
                     isMine ? 14 : 15, isMine ? optUserName : name, msg);
 
                 printMsgF(NULL, LOG_FILE, "½11½%s½0½\n", h);
-            } else {
+            }
+            else
+            {
                 printMsgF(NULL, isIgnored ? LOG_FILE : (LOG_WINDOW | LOG_FILE),
                     "½11½%s½0½\n", h);
             }
             th_free(name);
             th_free(h);
-        } else {
+        }
+        else
+        {
             /* It's an action (/me) */
             char *h = nn_decode_str2(t);
             printMsgF(NULL, isIgnored ? LOG_FILE : (LOG_WINDOW | LOG_FILE),
@@ -669,7 +721,9 @@
             th_free(h);
         }
         th_free(t);
-    } else {
+    }
+    else
+    {
         /* It's a normal message */
         char *h;
         t = nn_strip_tags(s);
@@ -690,17 +744,21 @@
 int handleLogin(nn_conn_t *conn, const char *str)
 {
     char tmpStr[256];
-    
+
     getTimeStamp(tmpStr, sizeof(tmpStr), "%c");
-    
-    if (!strncmp(str, "FAILURE", 7)) {
+
+    if (!strncmp(str, "FAILURE", 7))
+    {
         printMsg(NULL, "½1½Login failure½0½ - ½3½%s½0½\n", tmpStr);
         return -2;
-    } else if (!strncmp(str, "SUCCESS", 7)) {
+    }
+    else if (!strncmp(str, "SUCCESS", 7))
+    {
         printMsg(NULL, "½2½Login success½0½ - ½3½%s½0½\n", tmpStr);
         nn_conn_send_msg(conn, optUserNameEnc, "%%2FRequestUserList");
         return 0;
-    } else
+    }
+    else
         return 1;
 }
 
@@ -714,7 +772,7 @@
 
     if (!s) return 1;
     *s = 0;
-    
+
     p = nn_dbldecode_str(str);
     if (!p) return -1;
 
@@ -739,7 +797,7 @@
 
     if (!s) return 1;
     *s = 0;
-    
+
     p = nn_dbldecode_str(str);
     if (!p) return -1;
 
@@ -749,7 +807,7 @@
     printMsg(NULL, "! ½3½%s½0½ ½1½DELETED.½0½\n", p);
     if (win != NULL)
         printMsg(win, "! ½3½%s½0½ ½1½left the chat.½0½\n", p);
-        
+
     th_free(p);
     return 0;
 }
@@ -757,28 +815,32 @@
 
 int handleFoo(nn_conn_t *conn, const char *str)
 {
-    (void) conn; (void) str;
-    
+    (void) conn;
+    (void) str;
+
     return 0;
 }
 
 
 int handleBoot(nn_conn_t *conn, const char *str)
 {
-    (void) conn; (void) str;
+    (void) conn;
+    (void) str;
     errorMsg("Booted by server.\n");
     return -1;
 }
 
 
-typedef struct {
+typedef struct
+{
     char *cmd;
     ssize_t len;
     int (*handler)(nn_conn_t *, const char *);
 } protocmd_t;
 
 
-static protocmd_t protoCmds[] = {
+static protocmd_t protoCmds[] =
+{
     { "<USER>",         -1, handleUser },
     { "<LOGIN_",        -1, handleLogin },
     { "<DELETE_USER>",  -1, handleDeleteUser },
@@ -795,22 +857,26 @@
     static BOOL protoCmdsInit = FALSE;
     int i;
 
-    if (!protoCmdsInit) {
+    if (!protoCmdsInit)
+    {
         for (i = 0; i < nprotoCmds; i++)
             protoCmds[i].len = strlen(protoCmds[i].cmd);
         protoCmdsInit = TRUE;
     }
-    
-    for (i = 0; i < nprotoCmds; i++) {
+
+    for (i = 0; i < nprotoCmds; i++)
+    {
         ssize_t cmdLen = protoCmds[i].len;
         if (cmdLen < bufLen && !strncmp(buf, protoCmds[i].cmd, cmdLen))
             return protoCmds[i].handler(conn, buf + cmdLen);
     }
 
-    if (optDebug) {
+    if (optDebug)
+    {
         printMsg(NULL, "Unknown protocmd: \"%s\"\n", buf);
         return 0;
-    } else
+    }
+    else
         return 1;
 }
 
@@ -829,7 +895,7 @@
 {
     char *tmpStr, tmpBuf[4096];
     BOOL result;
-    
+
     /* Trim right */
     bufLen--;
     buf[bufLen--] = 0;
@@ -838,15 +904,18 @@
 
     /* Decode completed usernames */
     nn_username_decode(buf);
-    
+
     /* Check for special user commands */
-    if (*buf == 0) {
+    if (*buf == 0)
+    {
         return 1;
     }
-    else if (!th_strncasecmp(buf, "/color ", 7)) {
+    else if (!th_strncasecmp(buf, "/color ", 7))
+    {
         /* Change color */
         int tmpInt;
-        if ((tmpInt = th_get_hex_triplet(trimLeft(buf + 7))) < 0) {
+        if ((tmpInt = th_get_hex_triplet(trimLeft(buf + 7))) < 0)
+        {
             printMsgQ(currWin, "Invalid color value '%s'\n", buf+7);
             return 1;
         }
@@ -855,25 +924,34 @@
         nn_conn_send_msg(conn, optUserNameEnc, "%%2FSetFontColor%%20%%2Dcolor%%20%06X", optUserColor);
         return 0;
     }
-    else if (!th_strncasecmp(buf, "/ignore", 7)) {
+    else if (!th_strncasecmp(buf, "/ignore", 7))
+    {
         char *name = trimLeft(buf + 7);
-        if (strlen(name) > 0) {
+        if (strlen(name) > 0)
+        {
             /* Add or remove someone to/from ignore */
             qlist_t *user = th_llist_find_func(setIgnoreList, name, compareUsername);
-            if (user != NULL) {
+            if (user != NULL)
+            {
                 printMsgQ(currWin, "Removed user '%s' from ignore.\n", name);
                 th_llist_delete_node(&setIgnoreList, user);
-            } else {
+            }
+            else
+            {
                 printMsgQ(currWin, "Now ignoring '%s'.\n", name);
                 th_llist_append(&setIgnoreList, th_strdup(name));
             }
-        } else {
+        }
+        else
+        {
             /* Just list whomever is in ignore now */
             qlist_t *user = setIgnoreList;
             ssize_t nuser = th_llist_length(setIgnoreList);
             char *result = th_strdup_printf("Users ignored (%d): ", nuser);
-            while (user != NULL) {
-                if (user->data != NULL) {
+            while (user != NULL)
+            {
+                if (user->data != NULL)
+                {
                     th_pstr_printf(&result, "%s'%s'", result, (char *) user->data);
                     if (--nuser > 0)
                         th_pstr_printf(&result, "%s, ", result);
@@ -885,64 +963,86 @@
         }
         return 0;
     }
-    else if (!th_strncasecmp(buf, "/query", 6)) {
+    else if (!th_strncasecmp(buf, "/query", 6))
+    {
         char *name = trimLeft(buf + 6);
-        if (strlen(name) > 0) {
+        if (strlen(name) > 0)
+        {
             nn_user_t *user = nn_user_find(nnUsers, nn_username_encode(name));
-            if (user != NULL) {
+            if (user != NULL)
+            {
                 name = nn_username_decode(th_strdup(user->name));
                 printMsgQ(currWin, "Opening PRV query for '%s'.\n", name);
                 if (openWindow(name, TRUE))
                     printMsgQ(currWin, "In PRV query with '%s'.\n", name);
                 th_free(name);
             }
-        } else {
+        }
+        else
+        {
             printMsgQ(currWin, "Usage: /query username\n");
             printMsgQ(currWin, "To close a PRV query, use /close [username]\n");
             printMsgQ(currWin, "/close without username will close the current PRV window.\n");
         }
         return 0;
     }
-    else if (!th_strncasecmp(buf, "/win", 4)) {
+    else if (!th_strncasecmp(buf, "/win", 4))
+    {
         /* Change color */
         char *tmp = trimLeft(buf + 4);
-        if (strlen(tmp) > 0) {
+        if (strlen(tmp) > 0)
+        {
             int val = atoi(tmp);
-            if (val >= 1 && val < SET_MAX_WINDOWS) {
+            if (val >= 1 && val < SET_MAX_WINDOWS)
+            {
                 if (chatWindows[val - 1] != NULL)
                     currWin = chatWindows[val - 1];
-            } else {
+            }
+            else
+            {
                 printMsgQ(currWin, "Invalid window number '%s'\n", tmp);
                 return 1;
             }
-        } else {
+        }
+        else
+        {
             printMsgQ(currWin, "Window   : #%d\n", currWin->num);
             printMsgQ(currWin, "ID       : %s\n", currWin->id);
         }
         return 0;
     }
-    else if (!th_strncasecmp(buf, "/close", 6)) {
+    else if (!th_strncasecmp(buf, "/close", 6))
+    {
         char *name = trimLeft(buf + 6);
-        if (strlen(name) > 0) {
+        if (strlen(name) > 0)
+        {
             nn_window_t *win = findWindow(name);
-            if (win != NULL) {
+            if (win != NULL)
+            {
                 closeWindow(win);
                 printMsgQ(currWin, "Closed PRV query to '%s'.\n", name);
-            } else {
+            }
+            else
+            {
                 printMsgQ(currWin, "No PRV query by name '%s'.\n", name);
             }
-        } else {
-            if (currWin != chatWindows[0]) {
+        }
+        else
+        {
+            if (currWin != chatWindows[0])
+            {
                 closeWindow(currWin);
                 currWin = chatWindows[0];
             }
         }
         return 0;
     }
-    else if (!th_strncasecmp(buf, "/save", 5)) {
+    else if (!th_strncasecmp(buf, "/save", 5))
+    {
         /* Save configuration */
         FILE *cfgfile = fopen(setConfigFile, "w");
-        if (cfgfile == NULL) {
+        if (cfgfile == NULL)
+        {
             printMsgQ(currWin, "Could not create configuration to file '%s': %s\n",
                 setConfigFile, strerror(errno));
             return 0;
@@ -954,7 +1054,8 @@
         fclose(cfgfile);
         return 0;
     }
-    else if (!th_strncasecmp(buf, "/w ", 3)) {
+    else if (!th_strncasecmp(buf, "/w ", 3))
+    {
         /* Open given username's profile via firefox in a new tab */
         char *name = trimLeft(buf + 3);
 
@@ -963,52 +1064,61 @@
         tmpStr = nn_encode_str1(name);
 #ifdef __WIN32
         {
-        HINSTANCE status;
-        snprintf(tmpBuf, sizeof(tmpBuf), "http://www.newbienudes.com/profile/%s/", tmpStr);
-        th_free(tmpStr);
-        status = ShellExecute(NULL, "open", tmpBuf, NULL, NULL, SW_SHOWNA);
-        if (status <= (HINSTANCE) 32)
-            printMsgQ(currWin, "Could not launch default web browser: %d\n", status);
+            HINSTANCE status;
+            snprintf(tmpBuf, sizeof(tmpBuf), "http://www.newbienudes.com/profile/%s/", tmpStr);
+            th_free(tmpStr);
+            status = ShellExecute(NULL, "open", tmpBuf, NULL, NULL, SW_SHOWNA);
+            if (status <= (HINSTANCE) 32)
+                printMsgQ(currWin, "Could not launch default web browser: %d\n", status);
         }
 #else
         {
-        int status;
-        int fds[2];
-        pid_t pid;
-        snprintf(tmpBuf, sizeof(tmpBuf), "openurl(http://www.newbienudes.com/profile/%s/,new-tab)", tmpStr);
-        th_free(tmpStr);
+            int status;
+            int fds[2];
+            pid_t pid;
+            snprintf(tmpBuf, sizeof(tmpBuf), "openurl(http://www.newbienudes.com/profile/%s/,new-tab)", tmpStr);
+            th_free(tmpStr);
+
+            if (pipe(fds) == -1)
+            {
+                int ret = errno;
+                printMsgQ(currWin, "Could not open process communication pipe! (%d, %s)\n", ret, strerror(ret));
+                return 0;
+            }
 
-        if (pipe(fds) == -1) {
-            int ret = errno;
-            printMsgQ(currWin, "Could not open process communication pipe! (%d, %s)\n", ret, strerror(ret));
-            return 0;
-        }
+            if ((pid = fork()) < 0)
+            {
+                printMsgQ(currWin, "Could not create sub-process!\n");
+            }
+            else if (pid == 0)
+            {
+                dup2(fds[1], STDOUT_FILENO);
+                dup2(fds[0], STDERR_FILENO);
+                execlp(setBrowser, setBrowser, "-remote", tmpBuf, (void *)NULL);
+                _exit(errno);
+            }
 
-        if ((pid = fork()) < 0) {
-            printMsgQ(currWin, "Could not create sub-process!\n");
-        } else if (pid == 0) {
-            dup2(fds[1], STDOUT_FILENO);
-            dup2(fds[0], STDERR_FILENO);
-            execlp(setBrowser, setBrowser, "-remote", tmpBuf, (void *)NULL);
-            _exit(errno);
-        }
-        
-        wait(&status);
+            wait(&status);
         }
 #endif
         return 0;
     }
-    else if (!th_strncasecmp(buf, "/who", 4)) {
+    else if (!th_strncasecmp(buf, "/who", 4))
+    {
         /* Alias /who to /listallusers */
         snprintf(tmpBuf, sizeof(tmpBuf), "/listallusers");
         buf = tmpBuf;
     }
 
-    if (currWin != chatWindows[0]) {
-        if (currWin->id != NULL) {
+    if (currWin != chatWindows[0])
+    {
+        if (currWin->id != NULL)
+        {
             snprintf(tmpBuf, sizeof(tmpBuf), "/prv -to %s -msg %s", currWin->id, buf);
             buf = tmpBuf;
-        } else {
+        }
+        else
+        {
             printMsgQ(NULL, "No target set, exiting prv mode.\n");
             return 1;
         }
@@ -1019,7 +1129,7 @@
     if (tmpStr == 0) return -2;
     result = nn_conn_send_msg(conn, optUserNameEnc, "%s", tmpStr);
     th_free(tmpStr);
-    
+
     return result ? 0 : -1;
 }
 
@@ -1035,13 +1145,13 @@
     int w, h;
 
     getmaxyx(stdscr, h, w);
-    
+
     closeWindows();
 
     mainWin = subwin(stdscr, h - 4, w, 0, 0);
     statusWin = subwin(stdscr, 1, w, h - 4, 0);
     editWin = subwin(stdscr, 3, w, h - 3, 0);
-        
+
     if (mainWin == NULL || statusWin == NULL || editWin == NULL)
         return FALSE;
 
@@ -1064,36 +1174,45 @@
     ssize_t endPos, startPos = buf->pos;
 
     /* previous word */
-    if (startPos >= 2 && str[startPos - 1] == ' ' && str[startPos - 2] != ' ') {
+    if (startPos >= 2 && str[startPos - 1] == ' ' && str[startPos - 2] != ' ')
+    {
         startPos -= 2;
         endPos = startPos;
         while (startPos > 0 && str[startPos - 1] != ' ') startPos--;
         mode = 1;
-    } else
-    /* middle of a word, new pattern */
-    if (startPos < buf->len && str[startPos] != ' ') {
-        endPos = startPos;
-        while (startPos > 0 && str[startPos - 1] != ' ') startPos--;
-        while (endPos < buf->len - 1 && str[endPos + 1] != ' ') endPos++;
-        newPattern = TRUE;
-        mode = 2;
-    } else
-    /* previous word, new pattern */
-    if (startPos >= 1 && str[startPos - 1] != ' ') {
-        startPos -= 1;
-        endPos = startPos;
-        while (startPos > 0 && str[startPos - 1] != ' ') startPos--;
-        newPattern = TRUE;
-        mode = 3;
-    } else {
-        if (optDebug)
-            printMsg(currWin, "no mode\n");
-        return FALSE;
     }
+    else
+        /* middle of a word, new pattern */
+        if (startPos < buf->len && str[startPos] != ' ')
+        {
+            endPos = startPos;
+            while (startPos > 0 && str[startPos - 1] != ' ') startPos--;
+            while (endPos < buf->len - 1 && str[endPos + 1] != ' ') endPos++;
+            newPattern = TRUE;
+            mode = 2;
+        }
+        else
+            /* previous word, new pattern */
+            if (startPos >= 1 && str[startPos - 1] != ' ')
+            {
+                startPos -= 1;
+                endPos = startPos;
+                while (startPos > 0 && str[startPos - 1] != ' ') startPos--;
+                newPattern = TRUE;
+                mode = 3;
+            }
+            else
+            {
+                if (optDebug)
+                    printMsg(currWin, "no mode\n");
+                return FALSE;
+            }
 
-    if (str[endPos] == optNickSep) {
+    if (str[endPos] == optNickSep)
+    {
         endPos--;
-        if (startPos > 0) {
+        if (startPos > 0)
+        {
             if (optDebug)
                 printMsg(currWin, "str[endPos] == optNickSep && startPos > 0 (%d)\n", startPos);
             return FALSE;
@@ -1105,35 +1224,40 @@
         hasSpace = TRUE;
     if (buf->pos <= buf->len && str[buf->pos] == ' ')
         hasSpace = TRUE;
-    
-    if (newPattern) {
+
+    if (newPattern)
+    {
         /* Get pattern, check if it matches previous pattern and set 'again' flag */
         char *npattern = nn_editbuf_get_string(buf, startPos, endPos);
         if (pattern && npattern && th_strcasecmp(npattern, pattern) == 0)
             again = TRUE;
-        
+
         th_free(pattern);
         pattern = npattern;
-        
-        if (!again) {
+
+        if (!again)
+        {
             th_free(previous);
             previous = NULL;
         }
     }
 
-    if (optDebug) {
+    if (optDebug)
+    {
         printMsg(currWin, "sPos=%d, ePos=%d <-> bPos=%d, bufLen=%d : pat='%s' (again=%s, hassep=%s, hasspc=%s, newpat=%s, mode=%d)\n",
-                  startPos, endPos, buf->pos, buf->len, pattern,
-                  again ? "yes" : "no",
-                  hasSeparator ? "yes" : "no",
-                  hasSpace ? "yes" : "no",
-                  newPattern ? "yes" : "no", mode);
+                 startPos, endPos, buf->pos, buf->len, pattern,
+                 again ? "yes" : "no",
+                 hasSeparator ? "yes" : "no",
+                 hasSpace ? "yes" : "no",
+                 newPattern ? "yes" : "no", mode);
     }
 
-    if (pattern) {
+    if (pattern)
+    {
         nn_user_t *user = nn_user_match(nnUsers, pattern, previous, again);
 
-        if (user) {
+        if (user)
+        {
             int i;
             char *c = user->name;
             if (optDebug)
@@ -1141,11 +1265,12 @@
 
             for (i = startPos; i <= endPos; i++)
                 nn_editbuf_delete(buf, startPos);
-                
+
             for (i = startPos; *c; i++, c++)
                 nn_editbuf_insert(buf, i, *c);
 
-            if (!hasSeparator && startPos == 0) {
+            if (!hasSeparator && startPos == 0)
+            {
                 nn_editbuf_insert(buf, i++, optNickSep);
                 startPos++;
             }
@@ -1158,11 +1283,11 @@
 
             th_free(previous);
             previous = th_strdup(user->name);
-            
+
             return TRUE;
         }
     }
-    
+
     return FALSE;
 }
 
@@ -1175,32 +1300,37 @@
     char *bufData = th_malloc(bufSize);
     char tmpBuf[32];
     const char *s = fmt;
-    
-    while (*s) {
-        if (*s == '%') {
+
+    while (*s)
+    {
+        if (*s == '%')
+        {
             s++;
-            switch (*s) {
-                case 'i':
-                    snprintf(tmpBuf, sizeof(tmpBuf), "%05d", id);
-                    VPUTS(tmpBuf);
-                    break;
+            switch (*s)
+            {
+            case 'i':
+                snprintf(tmpBuf, sizeof(tmpBuf), "%05d", id);
+                VPUTS(tmpBuf);
+                break;
 
-                case 'd':
-                    snprintf(tmpBuf, sizeof(tmpBuf), "%d", id);
-                    VPUTS(tmpBuf);
-                    break;
+            case 'd':
+                snprintf(tmpBuf, sizeof(tmpBuf), "%d", id);
+                VPUTS(tmpBuf);
+                break;
 
-                case '%':
-                    VPUTCH('%');
-                    break;
+            case '%':
+                VPUTCH('%');
+                break;
             }
             s++;
-        } else {
+        }
+        else
+        {
             VPUTCH(*s);
             s++;
         }
     }
-    
+
     VPUTCH(0);
     return bufData;
 }
@@ -1209,18 +1339,19 @@
 BOOL logFileOpen(void)
 {
     char *filename;
-    
+
     if (optLogFilename == NULL || !optLogEnable)
         return FALSE;
 
     filename = logParseFilename(optLogFilename, optPort);
 
-    if ((optLogFile = fopen(filename, "a")) == NULL) {
+    if ((optLogFile = fopen(filename, "a")) == NULL)
+    {
         errorMsg("Could not open logfile '%s' for appending!\n", filename);
         th_free(filename);
         return FALSE;
     }
-    
+
     th_free(filename);
 
     return TRUE;
@@ -1228,7 +1359,8 @@
 
 void logFileClose(void)
 {
-    if (optLogFile) {
+    if (optLogFile)
+    {
         fclose(optLogFile);
         optLogFile = NULL;
     }
@@ -1246,7 +1378,7 @@
     noecho();
     if (curVis != ERR)
         curs_set(curVis);
-    
+
     for (pos = strlen(tmpBuf) - 1; pos > 0 && (tmpBuf[pos] == '\n' || tmpBuf[pos] == '\r' || th_isspace(tmpBuf[pos])); pos--)
         tmpBuf[pos] = 0;
 
@@ -1261,12 +1393,12 @@
 void printHelp(void)
 {
     printMsgQ(currWin, "\n"
-    "NNChat Help\n"
-    "===========\n"
-    "\n"
-    "F1             This help.\n"
-    "F2             \n"
-    );
+              "NNChat Help\n"
+              "===========\n"
+              "\n"
+              "F1             This help.\n"
+              "F2             \n"
+             );
 }
 
 int main(int argc, char *argv[])
@@ -1290,7 +1422,7 @@
     char *homeDir = NULL;
 
     memset(histBuf, 0, sizeof(histBuf));
-    
+
     /* Initialize */
     th_init("NNChat", "Newbie Nudes chat client", NN_VERSION,
         "Written and designed by Anonymous Finnish Guy (C) 2008-2011",
@@ -1304,7 +1436,7 @@
     th_cfg_add_string(&tmpcfg, "password", &optPassword, NULL);
     th_cfg_add_comment(&tmpcfg, "Default color as a hex-triplet");
     th_cfg_add_hexvalue(&tmpcfg, "color", &optUserColor, optUserColor);
-    
+
     th_cfg_add_comment(&tmpcfg, "Default setting of ignore mode");
     th_cfg_add_bool(&tmpcfg, "ignore", &setIgnoreMode, setIgnoreMode);
     th_cfg_add_comment(&tmpcfg, "People to be ignored when ignore mode is enabled");
@@ -1341,23 +1473,25 @@
 
 #ifdef __WIN32
     {
-    char tmpPath[MAX_PATH];
-    if (SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, tmpPath) == S_OK)
-        homeDir = th_strdup(tmpPath);
+        char tmpPath[MAX_PATH];
+        if (SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, tmpPath) == S_OK)
+            homeDir = th_strdup(tmpPath);
 
-    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
+        CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
     }
 #else
     homeDir = th_strdup(getenv("HOME"));
 #endif
-    
-    if (homeDir != NULL) {
+
+    if (homeDir != NULL)
+    {
         FILE *cfgfile;
         setConfigFile = th_strdup_printf("%s" SET_DIR_SEPARATOR "%s", homeDir, SET_CONFIG_FILE);
 
         THMSG(0, "Reading configuration from '%s'.\n", setConfigFile);
 
-        if ((cfgfile = fopen(setConfigFile, "r")) != NULL) {
+        if ((cfgfile = fopen(setConfigFile, "r")) != NULL)
+        {
             th_cfg_read(cfgfile, setConfigFile, cfg);
             fclose(cfgfile);
         }
@@ -1366,12 +1500,13 @@
     setBrowser = getenv("BROWSER");
     if (setBrowser == NULL)
         setBrowser = "firefox";
-    
+
     /* Parse command line arguments */
     argsOK = th_args_process(argc, argv, optList, optListN,
-        argHandleOpt, argHandleFile, FALSE);
+                             argHandleOpt, argHandleFile, FALSE);
 
-    if (optUserNameCmd != NULL) {
+    if (optUserNameCmd != NULL)
+    {
         optUserName = optUserNameCmd;
         optPassword = optPasswordCmd;
     }
@@ -1380,28 +1515,33 @@
         return -2;
 
     /* Allocate userhash */
-    if ((nnUsers = nn_userhash_new()) == NULL) {
+    if ((nnUsers = nn_userhash_new()) == NULL)
+    {
         THERR("Could not allocate userhash. Fatal error.\n");
         return -105;
     }
 
     /* If no idle messages are set, add default */
-    if (setIdleMessages == NULL) {
+    if (setIdleMessages == NULL)
+    {
         th_llist_append(&setIdleMessages, th_strdup("."));
     }
 
     /* Open logfile */
     logFileOpen();
-        
-    /* Initialize network */    
-    if (!nn_network_init()) {
+
+    /* Initialize network */
+    if (!nn_network_init())
+    {
         THERR("Could not initialize network subsystem.\n");
         goto err_exit;
-    } else
+    }
+    else
         networkInit = TRUE;
 
     /* Initialize NCurses */
-    if (!optDaemon) {
+    if (!optDaemon)
+    {
         if (LINES < 0 || LINES > 1000) LINES = 24;
         if (COLS < 0 || COLS > 1000) COLS = 80;
         initscr();
@@ -1412,9 +1552,10 @@
         timeout(SET_DELAY);
         curVis = curs_set(0);
 
-        if (has_colors()) {
+        if (has_colors())
+        {
             start_color();
-            
+
             init_pair( 1, COLOR_RED,     COLOR_BLACK);
             init_pair( 2, COLOR_GREEN,   COLOR_BLACK);
             init_pair( 3, COLOR_YELLOW,  COLOR_BLACK);
@@ -1432,9 +1573,9 @@
             init_pair(15, COLOR_MAGENTA, COLOR_RED);
             init_pair(16, COLOR_CYAN,    COLOR_RED);
         }
-        
+
         cursesInit = TRUE;
-        
+
         if (!initializeWindows())
             goto err_exit;
 
@@ -1444,42 +1585,48 @@
 
         memset(chatWindows, 0, sizeof(chatWindows));
         chatWindows[0] = nn_window_new(NULL);
-        currWin = chatWindows[0];        
+        currWin = chatWindows[0];
         updateStatus();
     }
 
     /* Check if we have username and password */
-    if (cursesInit && (optUserName == NULL || optPassword == NULL)) {
+    if (cursesInit && (optUserName == NULL || optPassword == NULL))
+    {
         printWin(editWin, "You can avoid this prompt by issuing '/save' after logging in.\n");
         optUserName = promptRequester(editWin, "NN username: ", FALSE);
         optPassword = promptRequester(editWin, "NN password: ", TRUE);
     }
-    
-    if (optUserName == NULL || optPassword == NULL) {
+
+    if (optUserName == NULL || optPassword == NULL)
+    {
         errorMsg("Username and/or password not specified.\n");
         goto err_exit;
     }
 
     /* Create a connection */
     conn = nn_conn_new(errorFunc, messageFunc);
-    if (conn == NULL) {
+    if (conn == NULL)
+    {
         errorMsg("Could not create connection structure.\n");
         goto err_exit;
     }
 
     /* Are we using a proxy? */
-    if (optProxyType != NN_PROXY_NONE && optProxyServer != NULL) {
-        if (nn_conn_set_proxy(conn, optProxyType, optProxyPort, optProxyServer) != 0) {
+    if (optProxyType != NN_PROXY_NONE && optProxyServer != NULL)
+    {
+        if (nn_conn_set_proxy(conn, optProxyType, optProxyPort, optProxyServer) != 0)
+        {
             errorMsg("Error setting proxy information.\n");
             goto err_exit;
         }
     }
-    
+
     /* Okay ... */
     printMsg(currWin, "Trying to resolve host '%s' ...\n", optServer);
     conn->host = th_strdup(optServer);
     conn->hst = nn_resolve_host(conn, optServer);
-    if (conn->hst == NULL) {
+    if (conn->hst == NULL)
+    {
         errorMsg("Could not resolve hostname: %s.\n", strerror(h_errno));
         goto err_exit;
     }
@@ -1488,20 +1635,27 @@
     /* To emulate the official client, we first make a request for
      * policy file, even though we don't use it for anything...
      */
-    if (nn_conn_open(conn, 843, NULL) != 0) {
+    if (nn_conn_open(conn, 843, NULL) != 0)
+    {
         errorMsg("Policy file request connection setup failed!\n");
         goto err_exit;
     }
 
     tmpStr = "<policy-file-request/>";
-    if (nn_conn_send_buf(conn, tmpStr, strlen(tmpStr) + 1) == FALSE) {
+    if (nn_conn_send_buf(conn, tmpStr, strlen(tmpStr) + 1) == FALSE)
+    {
         errorMsg("Failed to send policy file request.\n");
         goto err_exit;
-    } else {
+    }
+    else
+    {
         int cres = nn_conn_pull(conn);
-        if (cres == 0) {
+        if (cres == 0)
+        {
             printMsg(currWin, "Probe got: %s\n", conn->buf);
-        } else {
+        }
+        else
+        {
             printMsg(currWin, "Could not get policy probe.\n");
         }
     }
@@ -1509,22 +1663,24 @@
 #endif
 
     /* Okay, now do the proper connection ... */
-    if (nn_conn_open(conn, optPort, NULL) != 0) {
+    if (nn_conn_open(conn, optPort, NULL) != 0)
+    {
         errorMsg("Main connection setup failed!\n");
         goto err_exit;
     }
-    
+
     /* Send login command */
     optUserNameEnc = nn_dblencode_str(optUserName);
     tmpStr = nn_dblencode_str(optSite);
     nn_conn_send_msg(conn, optUserNameEnc, "%%2Flogin%%20%%2Dsite%%20%s%%20%%2Dpassword%%20%s", tmpStr, optPassword);
     th_free(tmpStr);
-    
+
     /* Initialize random numbers */
     prevTime = time(NULL);
     srandom((int) prevTime);
 
-    if (cursesInit) {
+    if (cursesInit)
+    {
         /* Initialize rest of interactive UI code */
         nn_editbuf_clear(editBuf);
 
@@ -1539,11 +1695,14 @@
 
     /* Enter mainloop */
     nn_conn_reset(conn);
-    while (!isError && !exitProg) {
+    while (!isError && !exitProg)
+    {
         int cres = nn_conn_pull(conn);
-        if (cres == 0 && *(conn->ptr - 1) == 0) {
+        if (cres == 0 && *(conn->ptr - 1) == 0)
+        {
             char *ptr = conn->buf;
-            do {
+            do
+            {
                 size_t bufLen = strlen(ptr) + 1;
                 int result = handleProtocol(conn, ptr, bufLen);
 
@@ -1561,36 +1720,48 @@
 
                 conn->total -= bufLen;
                 ptr += bufLen;
-            } while (conn->total > 0 && !isError);
+            }
+            while (conn->total > 0 && !isError);
             nn_conn_reset(conn);
         }
         if (!nn_conn_check(conn))
             isError = TRUE;
 
         /* Handle user input */
-        if (cursesInit) {
+        if (cursesInit)
+        {
             int c, cnt = 0;
             BOOL update = FALSE, updateMain = FALSE;
-            
+
             /* Handle several buffered keypresses at once */
-            do {
-            c = wgetch(stdscr);
-            if (c == 0x1b) {
+            do
+            {
                 c = wgetch(stdscr);
-                if (c == 'O') {
+                if (c == 0x1b)
+                {
                     c = wgetch(stdscr);
-                    switch (c) {
-                        case 'd': c = 0x204; break;
-                        case 'c': c = 0x206; break;
+                    if (c == 'O')
+                    {
+                        c = wgetch(stdscr);
+                        switch (c)
+                        {
+                        case 'd':
+                            c = 0x204;
+                            break;
+                        case 'c':
+                            c = 0x206;
+                            break;
                         default:
                             if (optDebug)
                                 printMsg(currWin, "Unhandled ESC-O key sequence 0x%02x\n", c);
                             break;
+                        }
                     }
-                } else
-                if (c == '[') {
-                    c = wgetch(stdscr);
-                    switch (c) {
+                    else if (c == '[')
+                    {
+                        c = wgetch(stdscr);
+                        switch (c)
+                        {
                         case 0x31:
                             c = wgetch(stdscr);
                             if (c >= 0x31 && c <= 0x39)
@@ -1598,277 +1769,321 @@
                             else
                                 c = ERR;
                             break;
-                        
-                        case 0x32: c = KEY_IC; break;
-                        case 0x33: c = KEY_DC; break;
+
+                        case 0x32:
+                            c = KEY_IC;
+                            break;
+                        case 0x33:
+                            c = KEY_DC;
+                            break;
 
-                        case 0x35: c = KEY_PPAGE; break;
-                        case 0x36: c = KEY_NPAGE; break;
+                        case 0x35:
+                            c = KEY_PPAGE;
+                            break;
+                        case 0x36:
+                            c = KEY_NPAGE;
+                            break;
 
-                        case 0x37: c = KEY_HOME; break;
-                        case 0x38: c = KEY_END; break;
-                        
+                        case 0x37:
+                            c = KEY_HOME;
+                            break;
+                        case 0x38:
+                            c = KEY_END;
+                            break;
+
                         default:
                             if (optDebug)
                                 printMsg(currWin, "Unhandled ESC-[*~ key sequence 0x%02x\n", c);
                             c = ERR;
                             break;
+                        }
+                        /* Get the trailing ~ */
+                        if (c != ERR)
+                            wgetch(stdscr);
                     }
-                    /* Get the trailing ~ */
-                    if (c != ERR)
-                        wgetch(stdscr);
+                    if (c >= 0x31 && c <= 0x39)
+                    {
+                        /* Chat window switching via Meta/Esc-[1..9] */
+                        int win = c - 0x31;
+                        if (win < SET_MAX_WINDOWS && chatWindows[win] != NULL)
+                        {
+                            currWin = chatWindows[win];
+                            update = updateMain = TRUE;
+                        }
+                        c = ERR;
+                    }
+                    else
+                    {
+                        if (optDebug)
+                            printMsg(currWin, "Unhandled ESC key sequence 0x%02x\n", c);
+                    }
                 }
-                if (c >= 0x31 && c <= 0x39) {
+#if defined(__WIN32) && defined(PDCURSES)
+                else if (c >= 0x198 && c <= 0x1a0)
+                {
                     /* Chat window switching via Meta/Esc-[1..9] */
-                    int win = c - 0x31;
-                    if (win < SET_MAX_WINDOWS && chatWindows[win] != NULL) {
+                    int win = c - 0x198;
+                    if (win < SET_MAX_WINDOWS && chatWindows[win] != NULL)
+                    {
                         currWin = chatWindows[win];
                         update = updateMain = TRUE;
                     }
                     c = ERR;
                 }
-                else {
-                    if (optDebug)
-                        printMsg(currWin, "Unhandled ESC key sequence 0x%02x\n", c);
-                }
-            }
-#if defined(__WIN32) && defined(PDCURSES)
-            else
-            if (c >= 0x198 && c <= 0x1a0) {
-                /* Chat window switching via Meta/Esc-[1..9] */
-                int win = c - 0x198;
-                if (win < SET_MAX_WINDOWS && chatWindows[win] != NULL) {
-                    currWin = chatWindows[win];
+#endif
+
+                switch (c)
+                {
+#ifdef KEY_RESIZE
+                case KEY_RESIZE:
+                    resize_term(0, 0);
+                    erase();
+                    timeout(SET_DELAY);
+
+                    if (!initializeWindows())
+                    {
+                        errorMsg("Error resizing curses chatWindows\n");
+                        isError = TRUE;
+                    }
                     update = updateMain = TRUE;
-                }
-                c = ERR;
-            }
+                    break;
 #endif
 
-            switch (c) {
-#ifdef KEY_RESIZE
-            case KEY_RESIZE:
-                resize_term(0, 0);
-                erase();
-                timeout(SET_DELAY);
+                case KEY_ENTER:
+                case '\n':
+                case '\r':
+                    /* Call the user input handler */
+                    if (editBuf->len > 0)
+                    {
+                        int result;
+
+                        if (histMax > 0)
+                        {
+                            nn_editbuf_free(histBuf[SET_MAX_HISTORY+1]);
+                            histBuf[SET_MAX_HISTORY+1] = NULL;
+                            memmove(&histBuf[2], &histBuf[1], histMax * sizeof(histBuf[0]));
+                        }
 
-                if (!initializeWindows())
-                {
-                    errorMsg("Error resizing curses chatWindows\n");
-                    isError = TRUE;
-                }
-                update = updateMain = TRUE;
-                break;
-#endif
-            
-            case KEY_ENTER:
-            case '\n':
-            case '\r':
-                /* Call the user input handler */
-                if (editBuf->len > 0) {
-                    int result;
-                    
-                    if (histMax > 0) {
-                        nn_editbuf_free(histBuf[SET_MAX_HISTORY+1]);
-                        histBuf[SET_MAX_HISTORY+1] = NULL;
-                        memmove(&histBuf[2], &histBuf[1], histMax * sizeof(histBuf[0]));
+                        histPos = 0;
+                        histBuf[1] = nn_editbuf_copy(editBuf);
+                        if (histMax < SET_MAX_HISTORY) histMax++;
+
+                        nn_editbuf_insert(editBuf, editBuf->len, 0);
+                        result = handleUserInput(conn, editBuf->data, editBuf->len);
+
+                        nn_editbuf_clear(editBuf);
+
+                        if (result < 0)
+                        {
+                            errorMsg("Fatal error handling user input: %s\n", editBuf->data);
+                            isError = TRUE;
+                        }
+                        else
+                        {
+                            /* Update time value of last sent message for unidle timeouts */
+                            prevTime = time(NULL);
+                        }
+
+                        updateMain = update = TRUE;
                     }
-                    
-                    histPos = 0;
-                    histBuf[1] = nn_editbuf_copy(editBuf);
-                    if (histMax < SET_MAX_HISTORY) histMax++;
-                    
-                    nn_editbuf_insert(editBuf, editBuf->len, 0);
-                    result = handleUserInput(conn, editBuf->data, editBuf->len);
-                    
-                    nn_editbuf_clear(editBuf);
-                    
-                    if (result < 0)
+                    break;
+
+                case KEY_UP: /* Backwards in input history */
+                    if (histPos == 0)
+                    {
+                        nn_editbuf_free(histBuf[0]);
+                        histBuf[0] = nn_editbuf_copy(editBuf);
+                    }
+                    if (histPos < histMax)
                     {
-                        errorMsg("Fatal error handling user input: %s\n", editBuf->data);
-                        isError = TRUE;
-                    } else {
-                        /* Update time value of last sent message for unidle timeouts */
-                        prevTime = time(NULL);
+                        histPos++;
+                        nn_editbuf_free(editBuf);
+                        editBuf = nn_editbuf_copy(histBuf[histPos]);
+                        update = TRUE;
                     }
-                    
-                    updateMain = update = TRUE;
-                }
-                break;
-            
-            case KEY_UP: /* Backwards in input history */
-                if (histPos == 0) {
-                    nn_editbuf_free(histBuf[0]);
-                    histBuf[0] = nn_editbuf_copy(editBuf);
-                }
-                if (histPos < histMax) {
-                    histPos++;
-                    nn_editbuf_free(editBuf);
-                    editBuf = nn_editbuf_copy(histBuf[histPos]);
+                    break;
+
+                case KEY_DOWN: /* Forwards in input history */
+                    if (histPos > 0)
+                    {
+                        histPos--;
+                        nn_editbuf_free(editBuf);
+                        editBuf = nn_editbuf_copy(histBuf[histPos]);
+                        update = TRUE;
+                    }
+                    break;
+
+                case 0x204: /* ctrl+left arrow = Skip words left */
+                case 0x20b:
+                    while (editBuf->pos > 0 && isspace((int) editBuf->data[editBuf->pos - 1]))
+                        editBuf->pos--;
+                    while (editBuf->pos > 0 && !isspace((int) editBuf->data[editBuf->pos - 1]))
+                        editBuf->pos--;
                     update = TRUE;
-                }
-                break;
-                
-            case KEY_DOWN: /* Forwards in input history */
-                if (histPos > 0) {
-                    histPos--;
-                    nn_editbuf_free(editBuf);
-                    editBuf = nn_editbuf_copy(histBuf[histPos]);
+                    break;
+
+                case 0x206: /* ctrl+right arrow = Skip words right */
+                case 0x210:
+                    while (editBuf->pos < editBuf->len && isspace((int) editBuf->data[editBuf->pos]))
+                        editBuf->pos++;
+                    while (editBuf->pos < editBuf->len && !isspace((int) editBuf->data[editBuf->pos]))
+                        editBuf->pos++;
+                    update = TRUE;
+                    break;
+
+                case KEY_HOME:
+                    nn_editbuf_setpos(editBuf, 0);
                     update = TRUE;
-                }
-                break;
-                
-            case 0x204: /* ctrl+left arrow = Skip words left */
-            case 0x20b:
-                while (editBuf->pos > 0 && isspace((int) editBuf->data[editBuf->pos - 1]))
-                    editBuf->pos--;
-                while (editBuf->pos > 0 && !isspace((int) editBuf->data[editBuf->pos - 1]))
-                    editBuf->pos--;
-                update = TRUE;
-                break;
-            
-            case 0x206: /* ctrl+right arrow = Skip words right */
-            case 0x210:
-                while (editBuf->pos < editBuf->len && isspace((int) editBuf->data[editBuf->pos]))
-                    editBuf->pos++;
-                while (editBuf->pos < editBuf->len && !isspace((int) editBuf->data[editBuf->pos]))
-                    editBuf->pos++;
-                update = TRUE;
-                break;
+                    break;
+                case KEY_END:
+                    nn_editbuf_setpos(editBuf, editBuf->len);
+                    update = TRUE;
+                    break;
+                case KEY_LEFT:
+                    nn_editbuf_setpos(editBuf, editBuf->pos - 1);
+                    update = TRUE;
+                    break;
+                case KEY_RIGHT:
+                    nn_editbuf_setpos(editBuf, editBuf->pos + 1);
+                    update = TRUE;
+                    break;
 
-            case KEY_HOME:  nn_editbuf_setpos(editBuf, 0); update = TRUE; break;
-            case KEY_END:   nn_editbuf_setpos(editBuf, editBuf->len); update = TRUE; break;
-            case KEY_LEFT:  nn_editbuf_setpos(editBuf, editBuf->pos - 1); update = TRUE; break;
-            case KEY_RIGHT: nn_editbuf_setpos(editBuf, editBuf->pos + 1); update = TRUE; break;
-            
-            case KEY_BACKSPACE:
-            case 0x08:
-            case 0x7f:
-                nn_editbuf_delete(editBuf, editBuf->pos - 1);
-                nn_editbuf_setpos(editBuf, editBuf->pos - 1);
-                update = TRUE;
-                break;
-            
-            case KEY_DC: /* Delete character */
-                nn_editbuf_delete(editBuf, editBuf->pos);
-                update = TRUE;
-                break;
-                
+                case KEY_BACKSPACE:
+                case 0x08:
+                case 0x7f:
+                    nn_editbuf_delete(editBuf, editBuf->pos - 1);
+                    nn_editbuf_setpos(editBuf, editBuf->pos - 1);
+                    update = TRUE;
+                    break;
+
+                case KEY_DC: /* Delete character */
+                    nn_editbuf_delete(editBuf, editBuf->pos);
+                    update = TRUE;
+                    break;
+
 
-            case KEY_IC: /* Ins = Toggle insert / overwrite mode */
-                insertMode = !insertMode;
-                update = TRUE;
-                break;
-            
-            case KEY_F(1): /* F1 = Print help */
-                printHelp();
-                updateMain = TRUE;
-                break;
+                case KEY_IC: /* Ins = Toggle insert / overwrite mode */
+                    insertMode = !insertMode;
+                    update = TRUE;
+                    break;
+
+                case KEY_F(1): /* F1 = Print help */
+                    printHelp();
+                    updateMain = TRUE;
+                    break;
 
-            case KEY_F(2): /* F2 = Clear editbuffer */
-                nn_editbuf_clear(editBuf);
-                update = TRUE;
-                break;
+                case KEY_F(2): /* F2 = Clear editbuffer */
+                    nn_editbuf_clear(editBuf);
+                    update = TRUE;
+                    break;
 
-            case KEY_F(5): /* F5 = Ignore mode */
-                setIgnoreMode = !setIgnoreMode;
-                printMsgQ(currWin, "Ignore mode = %s\n", setIgnoreMode ? "ON" : "OFF");
-                break;
+                case KEY_F(5): /* F5 = Ignore mode */
+                    setIgnoreMode = !setIgnoreMode;
+                    printMsgQ(currWin, "Ignore mode = %s\n", setIgnoreMode ? "ON" : "OFF");
+                    break;
 
 #if 0
-            case KEY_F(8): /* F8 = Debug */
-                optDebug = !optDebug;
-                update = TRUE;
-                break;
+                case KEY_F(8): /* F8 = Debug */
+                    optDebug = !optDebug;
+                    update = TRUE;
+                    break;
 #endif
-            
-            case 0x03: /* ^C = quit */
-            case KEY_F(9): /* F9 = Quit */
-                printMsg(currWin, "Quitting per user request (%d/0x%x).\n", c, c);
-                exitProg = TRUE;
-                break;
-            
-            case 0x09: /* Tab = complete username */
-                performTabCompletion(editBuf);
-                update = TRUE;
-                break;
-            
-            case 0x0c: /* Ctrl + L */
-                updateWindows();
-                update = updateMain = TRUE;
-                break;
+
+                case 0x03: /* ^C = quit */
+                case KEY_F(9): /* F9 = Quit */
+                    printMsg(currWin, "Quitting per user request (%d/0x%x).\n", c, c);
+                    exitProg = TRUE;
+                    break;
+
+                case 0x09: /* Tab = complete username */
+                    performTabCompletion(editBuf);
+                    update = TRUE;
+                    break;
 
-            case KEY_NPAGE:
-            case KEY_PPAGE:
-                /* Page Up / Page Down */
-                if (currWin != NULL)
-                {
-                int oldPos = currWin->pos;
+                case 0x0c: /* Ctrl + L */
+                    updateWindows();
+                    update = updateMain = TRUE;
+                    break;
 
-                currWin->pos += (c == KEY_NPAGE) ? -10 : +10;
+                case KEY_NPAGE:
+                case KEY_PPAGE:
+                    /* Page Up / Page Down */
+                    if (currWin != NULL)
+                    {
+                        int oldPos = currWin->pos;
+
+                        currWin->pos += (c == KEY_NPAGE) ? -10 : +10;
 
-                if (currWin->pos < 0)
-                    currWin->pos = 0;
-                else if (currWin->pos >= currWin->data->n - 10)
-                    currWin->pos = currWin->data->n - 10;
+                        if (currWin->pos < 0)
+                            currWin->pos = 0;
+                        else if (currWin->pos >= currWin->data->n - 10)
+                            currWin->pos = currWin->data->n - 10;
 
-                if (oldPos != currWin->pos)
-                    updateMain = TRUE;
-                }
-                break;
+                        if (oldPos != currWin->pos)
+                            updateMain = TRUE;
+                    }
+                    break;
+
+                case ERR:
+                    /* Ignore */
+                    break;
 
-            case ERR:
-                /* Ignore */
-                break;
-                
-            default:
-                if (isprint(c) || c == 0xe4 || c == 0xf6 || c == 0xc4 || c == 0xd6) {
-                    if (insertMode)
-                        nn_editbuf_insert(editBuf, editBuf->pos, c);
+                default:
+                    if (isprint(c) || c == 0xe4 || c == 0xf6 || c == 0xc4 || c == 0xd6)
+                    {
+                        if (insertMode)
+                            nn_editbuf_insert(editBuf, editBuf->pos, c);
+                        else
+                            nn_editbuf_write(editBuf, editBuf->pos, c);
+                        nn_editbuf_setpos(editBuf, editBuf->pos + 1);
+                        update = TRUE;
+                    }
                     else
-                        nn_editbuf_write(editBuf, editBuf->pos, c);
-                    nn_editbuf_setpos(editBuf, editBuf->pos + 1);
-                    update = TRUE; 
-                } else {
-                    if (optDebug)
-                        printMsg(currWin, "Unhandled key: 0x%02x\n", c);
+                    {
+                        if (optDebug)
+                            printMsg(currWin, "Unhandled key: 0x%02x\n", c);
+                    }
+                    break;
                 }
-                break;
             }
-            } while (c != ERR && !exitProg && ++cnt < 10);
-            
+            while (c != ERR && !exitProg && ++cnt < 10);
+
             updateMainWin(updateMain);
 
-            if (update || firstUpdate) {
+            if (update || firstUpdate)
+            {
                 /* Update edit line */
                 updateStatus();
                 printEditBuf(editBuf);
                 firstUpdate = FALSE; /* a nasty hack ... */
             }
-            
+
         } /* cursesInit */
-        
-        if (++updateCount > 10) {
+
+        if (++updateCount > 10)
+        {
             time_t tmpTime = time(NULL);
-            if (tmpTime - prevTime > SET_KEEPALIVE) {
+            if (tmpTime - prevTime > SET_KEEPALIVE)
+            {
                 int n = random() % th_llist_length(setIdleMessages);
                 qlist_t *node = th_llist_get_nth(setIdleMessages, n);
                 nn_conn_send_msg(conn, optUserNameEnc, node->data);
                 prevTime = tmpTime;
             }
-            
-            if (!colorSet) {
+
+            if (!colorSet)
+            {
                 colorSet = TRUE;
                 nn_conn_send_msg(conn, optUserNameEnc, "%%2FSetFontColor%%20%%2Dcolor%%20%06X", optUserColor);
             }
-            
+
             updateStatus();
             printEditBuf(editBuf);
             updateCount = 0;
         }
-        
+
     }
-    
+
     /* Shutdown */
 err_exit:
     th_cfg_free(cfg);
@@ -1878,16 +2093,17 @@
     nn_editbuf_free(editBuf);
 
     {
-    int i;
-    for (i = 0; i <= SET_MAX_HISTORY; i++)
-        nn_editbuf_free(histBuf[i]);
+        int i;
+        for (i = 0; i <= SET_MAX_HISTORY; i++)
+            nn_editbuf_free(histBuf[i]);
 
-    for (i = 0; i < SET_MAX_WINDOWS; i++)
-        nn_window_free(chatWindows[i]);
+        for (i = 0; i < SET_MAX_WINDOWS; i++)
+            nn_window_free(chatWindows[i]);
     }
 
 #ifdef __WIN32
-    if (errorMessages) {
+    if (errorMessages)
+    {
         char *tmp;
         wclear(editWin);
         tmp = promptRequester(editWin, "Press enter to quit.\n", FALSE);
@@ -1895,28 +2111,29 @@
     }
 #endif
 
-    if (cursesInit) {
+    if (cursesInit)
+    {
         if (curVis != ERR)
             curs_set(curVis);
         closeWindows();
         endwin();
         THMSG(1, "NCurses deinitialized.\n");
     }
-    
+
 #ifndef __WIN32
     if (errorMessages)
         THERR("%s", errorMessages);
 #endif
-    
+
     th_free(optUserNameEnc);
 
     nn_conn_close(conn);
-    
+
     if (networkInit)
         nn_network_close();
 
     THMSG(1, "Connection terminated.\n");
-    
+
     logFileClose();
 
     return 0;