Index: .gitignore
===================================================================
--- .gitignore	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ .gitignore	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -32,2 +32,3 @@
 bitlbee.service
 bitlbee@.service
+*.pyc
Index: configure
===================================================================
--- configure	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ configure	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -17,4 +17,5 @@
 libdir='$prefix/lib/'
 plugindir='$prefix/lib/bitlbee/'
+rpcplugindir='$plugindir/rpc/'
 includedir='$prefix/include/bitlbee/'
 systemdsystemunitdir=''
@@ -39,4 +40,5 @@
 twitter=1
 purple=0
+rpc=1
 
 verbose=0
@@ -124,4 +126,5 @@
 --datadir=...						$datadir
 --plugindir=...						$plugindir
+--rpcplugindir=...                                      $rpcplugindir
 --systemdsystemunitdir=...				$systemdsystemunitdir
 --pidfile=...						$pidfile
@@ -137,4 +140,5 @@
 --purple=0/1	Disable/enable libpurple support	$purple
 		(automatically disables other protocol modules)
+--rpc=0/1       Disable/enable RPC plugin interface     $rpc
 
 --pam=0/1	Disable/enable PAM authentication	$pam
@@ -176,4 +180,5 @@
 libdir=$(eval echo "$libdir/" | sed 's/\/\{1,\}/\//g')
 plugindir=$(eval echo "$plugindir/" | sed 's/\/\{1,\}/\//g')
+rpcplugindir=$(eval echo "$rpcplugindir/" | sed 's/\/\{1,\}/\//g')
 includedir=$(eval echo "$includedir"/ | sed 's/\/\{1,\}/\//g')
 libevent=$(eval echo "$libevent"/ | sed 's/\/\{1,\}/\//g')
@@ -197,4 +202,5 @@
 DATADIR=$datadir
 PLUGINDIR=$plugindir
+RPCPLUGINDIR=$rpcplugindir
 CONFIG=$config
 LIBDIR=$libdir
@@ -247,4 +253,5 @@
 #define VARDIR "$datadir"
 #define PLUGINDIR "$plugindir"
+#define RPCPLUGINDIR "$rpcplugindir"
 #define DATADIR "$datadir"
 #define PIDFILE "$pidfile"
@@ -288,4 +295,10 @@
 	LDFLAGS="$LDFLAGS -fsanitize=address"
 	debug=1
+fi
+
+if [ "$tsan" = "1" ]; then
+	echo
+	echo "Threaded BitlBee? Have a nice tall glass of http://imgur.com/gallery/tX4qxzS"
+	echo "No need to sanitise threads in a single-threaded process!"
 fi
 
@@ -730,4 +743,10 @@
 fi
 
+if [ "$rpc" = 0 ]; then
+	# Somewhat pointless at this stage already but at least this keeps it
+	# out of bitlbee.pc which is probably a good thing.
+	rpcplugindir=""
+fi
+
 otrprefix=""
 if [ "$otr" = "auto" ]; then
@@ -814,4 +833,5 @@
 includedir=$includedir
 plugindir=$plugindir
+rpcplugindir=$rpcplugindir
 libdir=$libdir
 datadir=$datadir
@@ -899,4 +919,12 @@
 	protocols=$protocols'twitter '
 	protoobjs=$protoobjs'twitter_mod.o '
+fi
+
+if [ "$rpc" = 0 ]; then
+	echo '#undef WITH_RPC' >> config.h
+else
+	echo '#define WITH_RPC' >> config.h
+	protocols=$protocols'rpc '
+	protoobjs=$protoobjs'rpc_mod.o '
 fi
 
@@ -990,5 +1018,4 @@
 echo '  Using event handler: '$events
 echo '  Using SSL library: '$ssl
-#echo '  Building with these storage backends: '$STORAGES
 
 if [ -n "$protocols" ]; then
Index: irc_channel.c
===================================================================
--- irc_channel.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ irc_channel.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -757,4 +757,9 @@
 	}
 
+	if (!bu->ic->acc->prpl->add_buddy) {
+		irc_send_num(ic->irc, 482, "%s :IM protocol does not support contact list modification", ic->name);
+		return FALSE;
+	}
+
 	bu->ic->acc->prpl->add_buddy(bu->ic, bu->handle,
 	                             icc->group ? icc->group->name : NULL);
@@ -774,4 +779,9 @@
 	if (icc->type != IRC_CC_TYPE_GROUP) {
 		irc_send_num(ic->irc, 482, "%s :Kicks are only possible to fill_by=group channels", ic->name);
+		return;
+	}
+
+	if (!bu->ic->acc->prpl->remove_buddy) {
+		irc_send_num(ic->irc, 482, "%s :IM protocol does not support contact list modification", ic->name);
 		return;
 	}
Index: irc_commands.c
===================================================================
--- irc_commands.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ irc_commands.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -330,5 +330,5 @@
 			   showed an error message, or is doing some work
 			   before the join should be confirmed. (In the
-			   latter case, the caller should take care of that
+			   latter case, the callee should take care of that
 			   confirmation.) TRUE means all's good, let the
 			   user join the channel right away. */
Index: lib/Makefile
===================================================================
--- lib/Makefile	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ lib/Makefile	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -13,5 +13,5 @@
 
 # [SH] Program variables
-objects = arc.o base64.o canohost.o $(EVENT_HANDLER) ftutil.o http_client.o ini.o json.o json_util.o md5.o misc.o oauth.o oauth2.o proxy.o sha1.o $(SSL_CLIENT) url.o xmltree.o ns_parse.o
+objects = arc.o base64.o canohost.o $(EVENT_HANDLER) ftutil.o http_client.o ini.o md5.o misc.o oauth.o oauth2.o parson.o proxy.o sha1.o $(SSL_CLIENT) url.o xmltree.o ns_parse.o
 
 LFLAGS += -r
Index: b/json.c
===================================================================
--- lib/json.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ 	(revision )
@@ -1,972 +1,0 @@
-/* vim: set et ts=3 sw=3 sts=3 ft=c:
- *
- * Copyright (C) 2012, 2013, 2014 James McLaughlin et al.  All rights reserved.
- * https://github.com/udp/json-parser
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *   notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <glib.h>
-
-#include "json.h"
-
-#ifdef _MSC_VER
-   #ifndef _CRT_SECURE_NO_WARNINGS
-      #define _CRT_SECURE_NO_WARNINGS
-   #endif
-#endif
-
-#ifdef __cplusplus
-const struct _json_value json_value_none;    /* zero-d by ctor */
-#else
-const struct _json_value json_value_none = { 0 };
-#endif
-
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-#include <math.h>
-
-typedef unsigned int json_uchar;
-
-static unsigned char hex_value(json_char c)
-{
-	if (g_ascii_isdigit(c)) {
-		return c - '0';
-	}
-
-	switch (c) {
-	case 'a': case 'A': return 0x0A;
-	case 'b': case 'B': return 0x0B;
-	case 'c': case 'C': return 0x0C;
-	case 'd': case 'D': return 0x0D;
-	case 'e': case 'E': return 0x0E;
-	case 'f': case 'F': return 0x0F;
-	default: return 0xFF;
-	}
-}
-
-typedef struct {
-	unsigned long used_memory;
-
-	unsigned int uint_max;
-	unsigned long ulong_max;
-
-	json_settings settings;
-	int first_pass;
-
-} json_state;
-
-static void * default_alloc(size_t size, int zero, void * user_data)
-{
-	return zero ? calloc(1, size) : malloc(size);
-}
-
-static void default_free(void * ptr, void * user_data)
-{
-	free(ptr);
-}
-
-static void * json_alloc(json_state * state, unsigned long size, int zero)
-{
-	if ((state->ulong_max - state->used_memory) < size) {
-		return 0;
-	}
-
-	if (state->settings.max_memory
-	    && (state->used_memory += size) > state->settings.max_memory) {
-		return 0;
-	}
-
-	return state->settings.mem_alloc(size, zero, state->settings.user_data);
-}
-
-static int new_value
-        (json_state * state, json_value ** top, json_value ** root, json_value ** alloc, json_type type)
-{
-	json_value * value;
-	int values_size;
-
-	if (!state->first_pass) {
-		value = *top = *alloc;
-		*alloc = (*alloc)->_reserved.next_alloc;
-
-		if (!*root) {
-			*root = value;
-		}
-
-		switch (value->type) {
-		case json_array:
-
-			if (!(value->u.array.values = (json_value **) json_alloc
-			                                      (state, value->u.array.length * sizeof(json_value *),
-			                                      0))) {
-				return 0;
-			}
-
-			value->u.array.length = 0;
-			break;
-
-		case json_object:
-
-			values_size = sizeof(*value->u.object.values) * value->u.object.length;
-
-			if (!((*(void **) &value->u.object.values) = json_alloc
-			                                                     (state, values_size +
-			                                                     ((unsigned long) value->u.object.values),
-			                                                     0))) {
-				return 0;
-			}
-
-			value->_reserved.object_mem = (*(char **) &value->u.object.values) + values_size;
-
-			value->u.object.length = 0;
-			break;
-
-		case json_string:
-
-			if (!(value->u.string.ptr = (json_char *) json_alloc
-			                                    (state, (value->u.string.length + 1) * sizeof(json_char),
-			                                    0))) {
-				return 0;
-			}
-
-			value->u.string.length = 0;
-			break;
-
-		default:
-			break;
-		}
-		;
-
-		return 1;
-	}
-
-	value = (json_value *) json_alloc(state, sizeof(json_value), 1);
-
-	if (!value) {
-		return 0;
-	}
-
-	if (!*root) {
-		*root = value;
-	}
-
-	value->type = type;
-	value->parent = *top;
-
-	if (*alloc) {
-		(*alloc)->_reserved.next_alloc = value;
-	}
-
-	*alloc = *top = value;
-
-	return 1;
-}
-
-#define e_off \
-	((int) (i - cur_line_begin))
-
-#define whitespace \
-case '\n': ++cur_line;  cur_line_begin = i; \
-case ' ': case '\t': case '\r'
-
-#define string_add(b)  \
-	do { if (!state.first_pass) { string [string_length] = b; } ++string_length; } while (0);
-
-static const long
-        flag_next             = 1 << 0,
-        flag_reproc           = 1 << 1,
-        flag_need_comma       = 1 << 2,
-        flag_seek_value       = 1 << 3,
-        flag_escaped          = 1 << 4,
-        flag_string           = 1 << 5,
-        flag_need_colon       = 1 << 6,
-        flag_done             = 1 << 7,
-        flag_num_negative     = 1 << 8,
-        flag_num_zero         = 1 << 9,
-        flag_num_e            = 1 << 10,
-        flag_num_e_got_sign   = 1 << 11,
-        flag_num_e_negative   = 1 << 12,
-        flag_line_comment     = 1 << 13,
-        flag_block_comment    = 1 << 14;
-
-json_value * json_parse_ex(json_settings * settings,
-                           const json_char * json,
-                           size_t length,
-                           char * error_buf)
-{
-	json_char error [json_error_max];
-	unsigned int cur_line;
-	const json_char * cur_line_begin, * i, * end;
-	json_value * top, * root, * alloc = 0;
-	json_state state = { 0 };
-	long flags;
-	long num_digits = 0, num_e = 0;
-	json_int_t num_fraction = 0;
-
-	/* Skip UTF-8 BOM
-	 */
-	if (length >= 3 && ((unsigned char) json [0]) == 0xEF
-	    && ((unsigned char) json [1]) == 0xBB
-	    && ((unsigned char) json [2]) == 0xBF) {
-		json += 3;
-		length -= 3;
-	}
-
-	error[0] = '\0';
-	end = (json + length);
-
-	memcpy(&state.settings, settings, sizeof(json_settings));
-
-	if (!state.settings.mem_alloc) {
-		state.settings.mem_alloc = default_alloc;
-	}
-
-	if (!state.settings.mem_free) {
-		state.settings.mem_free = default_free;
-	}
-
-	memset(&state.uint_max, 0xFF, sizeof(state.uint_max));
-	memset(&state.ulong_max, 0xFF, sizeof(state.ulong_max));
-
-	state.uint_max -= 8; /* limit of how much can be added before next check */
-	state.ulong_max -= 8;
-
-	for (state.first_pass = 1; state.first_pass >= 0; --state.first_pass) {
-		json_uchar uchar;
-		unsigned char uc_b1, uc_b2, uc_b3, uc_b4;
-		json_char * string = 0;
-		unsigned int string_length = 0;
-
-		top = root = 0;
-		flags = flag_seek_value;
-
-		cur_line = 1;
-		cur_line_begin = json;
-
-		for (i = json;; ++i) {
-			json_char b = (i == end ? 0 : *i);
-
-			if (flags & flag_string) {
-				if (!b) {
-					sprintf(error, "Unexpected EOF in string (at %d:%d)", cur_line, e_off);
-					goto e_failed;
-				}
-
-				if (string_length > state.uint_max) {
-					goto e_overflow;
-				}
-
-				if (flags & flag_escaped) {
-					flags &= ~flag_escaped;
-
-					switch (b) {
-					case 'b':  string_add('\b');  break;
-					case 'f':  string_add('\f');  break;
-					case 'n':  string_add('\n');  break;
-					case 'r':  string_add('\r');  break;
-					case 't':  string_add('\t');  break;
-					case 'u':
-
-						if (end - i < 4 ||
-						    (uc_b1 = hex_value(*++i)) == 0xFF || (uc_b2 = hex_value(*++i)) ==
-						    0xFF
-						    || (uc_b3 = hex_value(*++i)) == 0xFF || (uc_b4 = hex_value(*++i)) ==
-						    0xFF) {
-							sprintf(error, "Invalid character value `%c` (at %d:%d)", b,
-							        cur_line, e_off);
-							goto e_failed;
-						}
-
-						uc_b1 = (uc_b1 << 4) | uc_b2;
-						uc_b2 = (uc_b3 << 4) | uc_b4;
-						uchar = (uc_b1 << 8) | uc_b2;
-
-						if ((uchar & 0xF800) == 0xD800) {
-							json_uchar uchar2;
-
-							if (end - i < 6 || (*++i) != '\\' || (*++i) != 'u' ||
-							    (uc_b1 = hex_value(*++i)) == 0xFF ||
-							    (uc_b2 = hex_value(*++i)) == 0xFF
-							    || (uc_b3 = hex_value(*++i)) == 0xFF ||
-							    (uc_b4 = hex_value(*++i)) == 0xFF) {
-								sprintf(error,
-								        "Invalid character value `%c` (at %d:%d)", b,
-								        cur_line, e_off);
-								goto e_failed;
-							}
-
-							uc_b1 = (uc_b1 << 4) | uc_b2;
-							uc_b2 = (uc_b3 << 4) | uc_b4;
-							uchar2 = (uc_b1 << 8) | uc_b2;
-
-							uchar = 0x010000 | ((uchar & 0x3FF) << 10) | (uchar2 & 0x3FF);
-						}
-
-						if (sizeof(json_char) >= sizeof(json_uchar) || (uchar <= 0x7F)) {
-							string_add((json_char) uchar);
-							break;
-						}
-
-						if (uchar <= 0x7FF) {
-							if (state.first_pass) {
-								string_length += 2;
-							} else {                    string [string_length++] = 0xC0 |
-								                                               (uchar >>
-								                                                6);
-								                    string [string_length++] = 0x80 |
-								                                               (uchar &
-								                                                0x3F); }
-
-							break;
-						}
-
-						if (uchar <= 0xFFFF) {
-							if (state.first_pass) {
-								string_length += 3;
-							} else {                    string [string_length++] = 0xE0 |
-								                                               (uchar >>
-								                                                12);
-								                    string [string_length++] = 0x80 |
-								                                               ((uchar
-								                                                 >> 6) &
-								                                                0x3F);
-								                    string [string_length++] = 0x80 |
-								                                               (uchar &
-								                                                0x3F); }
-
-							break;
-						}
-
-						if (state.first_pass) {
-							string_length += 4;
-						} else {                string [string_length++] = 0xF0 | (uchar >> 18);
-							                string [string_length++] = 0x80 |
-							                                           ((uchar >>
-							                                             12) & 0x3F);
-							                string [string_length++] = 0x80 |
-							                                           ((uchar >>
-							                                             6) & 0x3F);
-							                string [string_length++] = 0x80 |
-							                                           (uchar & 0x3F); }
-
-						break;
-
-					default:
-						string_add(b);
-					}
-					;
-
-					continue;
-				}
-
-				if (b == '\\') {
-					flags |= flag_escaped;
-					continue;
-				}
-
-				if (b == '"') {
-					if (!state.first_pass) {
-						string [string_length] = 0;
-					}
-
-					flags &= ~flag_string;
-					string = 0;
-
-					switch (top->type) {
-					case json_string:
-
-						top->u.string.length = string_length;
-						flags |= flag_next;
-
-						break;
-
-					case json_object:
-
-						if (state.first_pass) {
-							(*(json_char **) &top->u.object.values) += string_length + 1;
-						} else {
-							top->u.object.values [top->u.object.length].name
-							        = (json_char *) top->_reserved.object_mem;
-
-							top->u.object.values [top->u.object.length].name_length
-							        = string_length;
-
-							(*(json_char **) &top->_reserved.object_mem) += string_length +
-							                                                1;
-						}
-
-						flags |= flag_seek_value | flag_need_colon;
-						continue;
-
-					default:
-						break;
-					}
-					;
-				} else {
-					string_add(b);
-					continue;
-				}
-			}
-
-			if (state.settings.settings & json_enable_comments) {
-				if (flags & (flag_line_comment | flag_block_comment)) {
-					if (flags & flag_line_comment) {
-						if (b == '\r' || b == '\n' || !b) {
-							flags &= ~flag_line_comment;
-							--i; /* so null can be reproc'd */
-						}
-
-						continue;
-					}
-
-					if (flags & flag_block_comment) {
-						if (!b) {
-							sprintf(error, "%d:%d: Unexpected EOF in block comment",
-							        cur_line, e_off);
-							goto e_failed;
-						}
-
-						if (b == '*' && i < (end - 1) && i [1] == '/') {
-							flags &= ~flag_block_comment;
-							++i; /* skip closing sequence */
-						}
-
-						continue;
-					}
-				} else if (b == '/') {
-					if (!(flags & (flag_seek_value | flag_done)) && top->type != json_object) {
-						sprintf(error, "%d:%d: Comment not allowed here", cur_line, e_off);
-						goto e_failed;
-					}
-
-					if (++i == end) {
-						sprintf(error, "%d:%d: EOF unexpected", cur_line, e_off);
-						goto e_failed;
-					}
-
-					switch (b = *i) {
-					case '/':
-						flags |= flag_line_comment;
-						continue;
-
-					case '*':
-						flags |= flag_block_comment;
-						continue;
-
-					default:
-						sprintf(error, "%d:%d: Unexpected `%c` in comment opening sequence",
-						        cur_line, e_off, b);
-						goto e_failed;
-					}
-					;
-				}
-			}
-
-			if (flags & flag_done) {
-				if (!b) {
-					break;
-				}
-
-				switch (b) {
-whitespace:
-					continue;
-
-				default:
-					sprintf(error, "%d:%d: Trailing garbage: `%c`", cur_line, e_off, b);
-					goto e_failed;
-				}
-				;
-			}
-
-			if (flags & flag_seek_value) {
-				switch (b) {
-whitespace:
-					continue;
-
-				case ']':
-
-					if (top && top->type == json_array) {
-						flags = (flags & ~(flag_need_comma | flag_seek_value)) | flag_next;
-					} else {              sprintf(error, "%d:%d: Unexpected ]", cur_line, e_off);
-						              goto e_failed; }
-
-					break;
-
-				default:
-
-					if (flags & flag_need_comma) {
-						if (b == ',') {
-							flags &= ~flag_need_comma;
-							continue;
-						} else { sprintf(error, "%d:%d: Expected , before %c", cur_line, e_off,
-							         b);
-							 goto e_failed; }
-					}
-
-					if (flags & flag_need_colon) {
-						if (b == ':') {
-							flags &= ~flag_need_colon;
-							continue;
-						} else { sprintf(error, "%d:%d: Expected : before %c", cur_line, e_off,
-							         b);
-							 goto e_failed; }
-					}
-
-					flags &= ~flag_seek_value;
-
-					switch (b) {
-					case '{':
-
-						if (!new_value(&state, &top, &root, &alloc, json_object)) {
-							goto e_alloc_failure;
-						}
-
-						continue;
-
-					case '[':
-
-						if (!new_value(&state, &top, &root, &alloc, json_array)) {
-							goto e_alloc_failure;
-						}
-
-						flags |= flag_seek_value;
-						continue;
-
-					case '"':
-
-						if (!new_value(&state, &top, &root, &alloc, json_string)) {
-							goto e_alloc_failure;
-						}
-
-						flags |= flag_string;
-
-						string = top->u.string.ptr;
-						string_length = 0;
-
-						continue;
-
-					case 't':
-
-						if ((end - i) < 3 || *(++i) != 'r' || *(++i) != 'u' || *(++i) != 'e') {
-							goto e_unknown_value;
-						}
-
-						if (!new_value(&state, &top, &root, &alloc, json_boolean)) {
-							goto e_alloc_failure;
-						}
-
-						top->u.boolean = 1;
-
-						flags |= flag_next;
-						break;
-
-					case 'f':
-
-						if ((end - i) < 4 || *(++i) != 'a' || *(++i) != 'l' || *(++i) != 's' ||
-						    *(++i) != 'e') {
-							goto e_unknown_value;
-						}
-
-						if (!new_value(&state, &top, &root, &alloc, json_boolean)) {
-							goto e_alloc_failure;
-						}
-
-						flags |= flag_next;
-						break;
-
-					case 'n':
-
-						if ((end - i) < 3 || *(++i) != 'u' || *(++i) != 'l' || *(++i) != 'l') {
-							goto e_unknown_value;
-						}
-
-						if (!new_value(&state, &top, &root, &alloc, json_null)) {
-							goto e_alloc_failure;
-						}
-
-						flags |= flag_next;
-						break;
-
-					default:
-
-						if (g_ascii_isdigit(b) || b == '-') {
-							if (!new_value(&state, &top, &root, &alloc, json_integer)) {
-								goto e_alloc_failure;
-							}
-
-							if (!state.first_pass) {
-								while (g_ascii_isdigit(b) || b == '+' || b == '-'
-								       || b == 'e' || b == 'E' || b == '.') {
-									if ((++i) == end) {
-										b = 0;
-										break;
-									}
-
-									b = *i;
-								}
-
-								flags |= flag_next | flag_reproc;
-								break;
-							}
-
-							flags &= ~(flag_num_negative | flag_num_e |
-							           flag_num_e_got_sign | flag_num_e_negative |
-							           flag_num_zero);
-
-							num_digits = 0;
-							num_fraction = 0;
-							num_e = 0;
-
-							if (b != '-') {
-								flags |= flag_reproc;
-								break;
-							}
-
-							flags |= flag_num_negative;
-							continue;
-						} else { sprintf(error, "%d:%d: Unexpected %c when seeking value",
-							         cur_line, e_off, b);
-							 goto e_failed; }
-					}
-					;
-				}
-				;
-			} else {
-				switch (top->type) {
-				case json_object:
-
-					switch (b) {
-whitespace:
-						continue;
-
-					case '"':
-
-						if (flags & flag_need_comma) {
-							sprintf(error, "%d:%d: Expected , before \"", cur_line, e_off);
-							goto e_failed;
-						}
-
-						flags |= flag_string;
-
-						string = (json_char *) top->_reserved.object_mem;
-						string_length = 0;
-
-						break;
-
-					case '}':
-
-						flags = (flags & ~flag_need_comma) | flag_next;
-						break;
-
-					case ',':
-
-						if (flags & flag_need_comma) {
-							flags &= ~flag_need_comma;
-							break;
-						}
-
-					default:
-
-						sprintf(error, "%d:%d: Unexpected `%c` in object", cur_line, e_off, b);
-						goto e_failed;
-					}
-					;
-
-					break;
-
-				case json_integer:
-				case json_double:
-
-					if (g_ascii_isdigit(b)) {
-						++num_digits;
-
-						if (top->type == json_integer || flags & flag_num_e) {
-							if (!(flags & flag_num_e)) {
-								if (flags & flag_num_zero) {
-									sprintf(error,
-									        "%d:%d: Unexpected `0` before `%c`",
-									        cur_line, e_off, b);
-									goto e_failed;
-								}
-
-								if (num_digits == 1 && b == '0') {
-									flags |= flag_num_zero;
-								}
-							} else {
-								flags |= flag_num_e_got_sign;
-								num_e = (num_e * 10) + (b - '0');
-								continue;
-							}
-
-							top->u.integer = (top->u.integer * 10) + (b - '0');
-							continue;
-						}
-
-						num_fraction = (num_fraction * 10) + (b - '0');
-						continue;
-					}
-
-					if (b == '+' || b == '-') {
-						if ((flags & flag_num_e) && !(flags & flag_num_e_got_sign)) {
-							flags |= flag_num_e_got_sign;
-
-							if (b == '-') {
-								flags |= flag_num_e_negative;
-							}
-
-							continue;
-						}
-					} else if (b == '.' && top->type == json_integer) {
-						if (!num_digits) {
-							sprintf(error, "%d:%d: Expected digit before `.`", cur_line,
-							        e_off);
-							goto e_failed;
-						}
-
-						top->type = json_double;
-						top->u.dbl = (double) top->u.integer;
-
-						num_digits = 0;
-						continue;
-					}
-
-					if (!(flags & flag_num_e)) {
-						if (top->type == json_double) {
-							if (!num_digits) {
-								sprintf(error, "%d:%d: Expected digit after `.`",
-								        cur_line, e_off);
-								goto e_failed;
-							}
-
-							top->u.dbl += ((double) num_fraction) /
-							              (pow(10, (double) num_digits));
-						}
-
-						if (b == 'e' || b == 'E') {
-							flags |= flag_num_e;
-
-							if (top->type == json_integer) {
-								top->type = json_double;
-								top->u.dbl = (double) top->u.integer;
-							}
-
-							num_digits = 0;
-							flags &= ~flag_num_zero;
-
-							continue;
-						}
-					} else {
-						if (!num_digits) {
-							sprintf(error, "%d:%d: Expected digit after `e`", cur_line,
-							        e_off);
-							goto e_failed;
-						}
-
-						top->u.dbl *=
-						        pow(10,
-						            (double) (flags & flag_num_e_negative ? -num_e : num_e));
-					}
-
-					if (flags & flag_num_negative) {
-						if (top->type == json_integer) {
-							top->u.integer = -top->u.integer;
-						} else {
-							top->u.dbl = -top->u.dbl;
-						}
-					}
-
-					flags |= flag_next | flag_reproc;
-					break;
-
-				default:
-					break;
-				}
-				;
-			}
-
-			if (flags & flag_reproc) {
-				flags &= ~flag_reproc;
-				--i;
-			}
-
-			if (flags & flag_next) {
-				flags = (flags & ~flag_next) | flag_need_comma;
-
-				if (!top->parent) {
-					/* root value done */
-
-					flags |= flag_done;
-					continue;
-				}
-
-				if (top->parent->type == json_array) {
-					flags |= flag_seek_value;
-				}
-
-				if (!state.first_pass) {
-					json_value * parent = top->parent;
-
-					switch (parent->type) {
-					case json_object:
-
-						parent->u.object.values
-						[parent->u.object.length].value = top;
-
-						break;
-
-					case json_array:
-
-						parent->u.array.values
-						[parent->u.array.length] = top;
-
-						break;
-
-					default:
-						break;
-					}
-					;
-				}
-
-				if ((++top->parent->u.array.length) > state.uint_max) {
-					goto e_overflow;
-				}
-
-				top = top->parent;
-
-				continue;
-			}
-		}
-
-		alloc = root;
-	}
-
-	return root;
-
-e_unknown_value:
-
-	sprintf(error, "%d:%d: Unknown value", cur_line, e_off);
-	goto e_failed;
-
-e_alloc_failure:
-
-	strcpy(error, "Memory allocation failure");
-	goto e_failed;
-
-e_overflow:
-
-	sprintf(error, "%d:%d: Too long (caught overflow)", cur_line, e_off);
-	goto e_failed;
-
-e_failed:
-
-	if (error_buf) {
-		if (*error) {
-			strcpy(error_buf, error);
-		} else {
-			strcpy(error_buf, "Unknown error");
-		}
-	}
-
-	if (state.first_pass) {
-		alloc = root;
-	}
-
-	while (alloc) {
-		top = alloc->_reserved.next_alloc;
-		state.settings.mem_free(alloc, state.settings.user_data);
-		alloc = top;
-	}
-
-	if (!state.first_pass) {
-		json_value_free_ex(&state.settings, root);
-	}
-
-	return 0;
-}
-
-json_value * json_parse(const json_char * json, size_t length)
-{
-	json_settings settings = { 0 };
-
-	return json_parse_ex(&settings, json, length, 0);
-}
-
-void json_value_free_ex(json_settings * settings, json_value * value)
-{
-	json_value * cur_value;
-
-	if (!value) {
-		return;
-	}
-
-	value->parent = 0;
-
-	while (value) {
-		switch (value->type) {
-		case json_array:
-
-			if (!value->u.array.length) {
-				settings->mem_free(value->u.array.values, settings->user_data);
-				break;
-			}
-
-			value = value->u.array.values [--value->u.array.length];
-			continue;
-
-		case json_object:
-
-			if (!value->u.object.length) {
-				settings->mem_free(value->u.object.values, settings->user_data);
-				break;
-			}
-
-			value = value->u.object.values [--value->u.object.length].value;
-			continue;
-
-		case json_string:
-
-			settings->mem_free(value->u.string.ptr, settings->user_data);
-			break;
-
-		default:
-			break;
-		}
-		;
-
-		cur_value = value;
-		value = value->parent;
-		settings->mem_free(cur_value, settings->user_data);
-	}
-}
-
-void json_value_free(json_value * value)
-{
-	json_settings settings = { 0 };
-
-	settings.mem_free = default_free;
-	json_value_free_ex(&settings, value);
-}
-
Index: b/json.h
===================================================================
--- lib/json.h	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ 	(revision )
@@ -1,262 +1,0 @@
-
-/* vim: set et ts=3 sw=3 sts=3 ft=c:
- *
- * Copyright (C) 2012, 2013, 2014 James McLaughlin et al.  All rights reserved.
- * https://github.com/udp/json-parser
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *   notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef _JSON_H
-#define _JSON_H
-
-#ifndef json_char
-   #define json_char char
-#endif
-
-#ifndef json_int_t
-   #ifndef _MSC_VER
-      #include <inttypes.h>
-      #define json_int_t int64_t
-   #else
-      #define json_int_t __int64
-   #endif
-#endif
-
-#include <stdlib.h>
-
-#ifdef __cplusplus
-
-   #include <string.h>
-
-extern "C"
-{
-
-#endif
-
-typedef struct {
-	unsigned long max_memory;
-	int settings;
-
-	/* Custom allocator support (leave null to use malloc/free)
-	 */
-
-	void * (*mem_alloc)(size_t, int zero, void * user_data);
-	void (* mem_free)(void *, void * user_data);
-
-	void * user_data; /* will be passed to mem_alloc and mem_free */
-
-} json_settings;
-
-#define json_enable_comments  0x01
-
-typedef enum {
-	json_none,
-	json_object,
-	json_array,
-	json_integer,
-	json_double,
-	json_string,
-	json_boolean,
-	json_null
-
-} json_type;
-
-extern const struct _json_value json_value_none;
-
-typedef struct _json_value {
-	struct _json_value * parent;
-
-	json_type type;
-
-	union {
-		int boolean;
-		json_int_t integer;
-		double dbl;
-
-		struct {
-			unsigned int length;
-			json_char * ptr; /* null terminated */
-
-		} string;
-
-		struct {
-			unsigned int length;
-
-			struct {
-				json_char * name;
-				unsigned int name_length;
-
-				struct _json_value * value;
-
-			} * values;
-
-	 #if defined(__cplusplus) && __cplusplus >= 201103L
-			decltype(values) begin() const
-			{  return values; }
-			decltype(values) end() const
-			{  return values + length; }
-	 #endif
-
-		} object;
-
-		struct {
-			unsigned int length;
-			struct _json_value ** values;
-
-	 #if defined(__cplusplus) && __cplusplus >= 201103L
-			decltype(values) begin() const
-			{  return values; }
-			decltype(values) end() const
-			{  return values + length; }
-	 #endif
-
-		} array;
-
-	} u;
-
-	union {
-		struct _json_value * next_alloc;
-		void * object_mem;
-
-	} _reserved;
-
-
-	/* Some C++ operator sugar */
-
-   #ifdef __cplusplus
-
-public:
-
-	inline _json_value ()
-	{
-		memset(this, 0, sizeof(_json_value));
-	}
-
-	inline const struct _json_value &operator [](int index) const
-	{
-		if (type != json_array || index < 0
-		    || ((unsigned int)index) >= u.array.length) {
-			return json_value_none;
-		}
-
-		return *u.array.values [index];
-	}
-
-	inline const struct _json_value &operator [](const char * index) const
-	{
-		if (type != json_object) {
-			return json_value_none;
-		}
-
-		for (unsigned int i = 0; i < u.object.length; ++i) {
-			if (!strcmp(u.object.values [i].name, index)) {
-				return *u.object.values [i].value;
-			}
-		}
-
-		return json_value_none;
-	}
-
-	inline operator const char *() const
-	{
-		switch (type) {
-		case json_string:
-			return u.string.ptr;
-
-		default:
-			return "";
-		}
-		;
-	}
-
-	inline operator json_int_t() const
-	{
-		switch (type) {
-		case json_integer:
-			return u.integer;
-
-		case json_double:
-			return (json_int_t)u.dbl;
-
-		default:
-			return 0;
-		}
-		;
-	}
-
-	inline operator bool() const
-	{
-		if (type != json_boolean) {
-			return false;
-		}
-
-		return u.boolean != 0;
-	}
-
-	inline operator double() const
-	{
-		switch (type) {
-		case json_integer:
-			return (double)u.integer;
-
-		case json_double:
-			return u.dbl;
-
-		default:
-			return 0;
-		}
-		;
-	}
-
-   #endif
-
-} json_value;
-
-json_value * json_parse(const json_char * json,
-                        size_t length);
-
-#define json_error_max 128
-json_value * json_parse_ex(json_settings * settings,
-                           const json_char * json,
-                           size_t length,
-                           char * error);
-
-void json_value_free(json_value *);
-
-
-/* Not usually necessary, unless you used a custom mem_alloc and now want to
- * use a custom mem_free.
- */
-void json_value_free_ex(json_settings * settings,
-                        json_value *);
-
-
-#ifdef __cplusplus
-}    /* extern "C" */
-#endif
-
-#endif
-
-
Index: b/json_util.c
===================================================================
--- lib/json_util.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ 	(revision )
@@ -1,67 +1,0 @@
-/***************************************************************************\
-*                                                                           *
-*  BitlBee - An IRC to IM gateway                                           *
-*  Helper functions for json.c                                              *
-*                                                                           *
-*  Copyright 2012-2012 Wilmer van der Gaast <wilmer@gaast.net>              *
-*                                                                           *
-*  This program is free software; you can redistribute it and/or modify     *
-*  it under the terms of the GNU General Public License as published by     *
-*  the Free Software Foundation; either version 2 of the License, or        *
-*  (at your option) any later version.                                      *
-*                                                                           *
-*  This program is distributed in the hope that it will be useful,          *
-*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
-*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
-*  GNU General Public License for more details.                             *
-*                                                                           *
-*  You should have received a copy of the GNU General Public License along  *
-*  with this program; if not, write to the Free Software Foundation, Inc.,  *
-*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
-*                                                                           *
-****************************************************************************/
-
-#include <stdlib.h>
-#include <string.h>
-#include <glib.h>
-
-#include "json_util.h"
-
-json_value *json_o_get(const json_value *obj, const json_char *name)
-{
-	int i;
-
-	if (!obj || obj->type != json_object) {
-		return NULL;
-	}
-
-	for (i = 0; i < obj->u.object.length; ++i) {
-		if (strcmp(obj->u.object.values[i].name, name) == 0) {
-			return obj->u.object.values[i].value;
-		}
-	}
-
-	return NULL;
-}
-
-const char *json_o_str(const json_value *obj, const json_char *name)
-{
-	json_value *ret = json_o_get(obj, name);
-
-	if (ret && ret->type == json_string) {
-		return ret->u.string.ptr;
-	} else {
-		return NULL;
-	}
-}
-
-char *json_o_strdup(const json_value *obj, const json_char *name)
-{
-	json_value *ret = json_o_get(obj, name);
-
-	if (ret && ret->type == json_string && ret->u.string.ptr) {
-		return g_memdup(ret->u.string.ptr, ret->u.string.length + 1);
-	} else {
-		return NULL;
-	}
-}
Index: b/json_util.h
===================================================================
--- lib/json_util.h	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ 	(revision )
@@ -1,35 +1,0 @@
-/***************************************************************************\
-*                                                                           *
-*  BitlBee - An IRC to IM gateway                                           *
-*  Helper functions for json.c                                              *
-*                                                                           *
-*  Copyright 2012-2012 Wilmer van der Gaast <wilmer@gaast.net>              *
-*                                                                           *
-*  This program is free software; you can redistribute it and/or modify     *
-*  it under the terms of the GNU General Public License as published by     *
-*  the Free Software Foundation; either version 2 of the License, or        *
-*  (at your option) any later version.                                      *
-*                                                                           *
-*  This program is distributed in the hope that it will be useful,          *
-*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
-*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
-*  GNU General Public License for more details.                             *
-*                                                                           *
-*  You should have received a copy of the GNU General Public License along  *
-*  with this program; if not, write to the Free Software Foundation, Inc.,  *
-*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
-*                                                                           *
-****************************************************************************/
-
-#include "json.h"
-
-#define JSON_O_FOREACH(o, k, v) \
-	char *k; json_value *v; int __i; \
-	for (__i = 0; (__i < (o)->u.object.length) && \
-	     (k = (o)->u.object.values[__i].name) && \
-	     (v = (o)->u.object.values[__i].value); \
-	     __i ++)
-
-json_value *json_o_get(const json_value *obj, const json_char *name);
-const char *json_o_str(const json_value *obj, const json_char *name);
-char *json_o_strdup(const json_value *obj, const json_char *name);
Index: lib/misc.c
===================================================================
--- lib/misc.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ lib/misc.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -386,5 +386,5 @@
 }
 
-int is_bool(char *value)
+int is_bool(const char *value)
 {
 	if (*value == 0) {
@@ -412,5 +412,5 @@
 }
 
-int bool2int(char *value)
+int bool2int(const char *value)
 {
 	int i;
Index: lib/misc.h
===================================================================
--- lib/misc.h	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ lib/misc.h	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -135,6 +135,6 @@
 G_MODULE_EXPORT void random_bytes(unsigned char *buf, int count);
 
-G_MODULE_EXPORT int is_bool(char *value);
-G_MODULE_EXPORT int bool2int(char *value);
+G_MODULE_EXPORT int is_bool(const char *value);
+G_MODULE_EXPORT int bool2int(const char *value);
 
 G_MODULE_EXPORT struct ns_srv_reply **srv_lookup(char *service, char *protocol, char *domain);
Index: lib/oauth2.c
===================================================================
--- lib/oauth2.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ lib/oauth2.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -42,7 +42,10 @@
 #include "oauth2.h"
 #include "oauth.h"
-#include "json.h"
-#include "json_util.h"
+#include "parson.h"
 #include "url.h"
+
+#define JSON_O_FOREACH(o, k, v) \
+    const char *k; const JSON_Value *v; int __i; \
+    for (__i = 0; json_object_get_tuple(o, __i, &k, &v); __i++)
 
 char *oauth2_url(const struct oauth2_service *sp)
@@ -113,23 +116,18 @@
 }
 
-static char* oauth2_parse_error(json_value *e)
+static char* oauth2_parse_error(const JSON_Value *e)
 {
 	/* This does a reasonable job with some of the flavours of error
 	   responses I've seen. Because apparently it's not standardised. */
 
-	if (e->type == json_object) {
+	if (json_type(e) == JSONObject) {
 		/* Facebook style */
-		const char *msg = json_o_str(e, "message");
-		const char *type = json_o_str(e, "type");
-		json_value *code_o = json_o_get(e, "code");
-		int code = 0;
-
-		if (code_o && code_o->type == json_integer) {
-			code = code_o->u.integer;
-		}
-
+		const char *msg = json_object_get_string(json_object(e), "message");
+		const char *type = json_object_get_string(json_object(e), "type");
+		JSON_Value *code_o = json_object_get_value(json_object(e), "code");
+		int code = json_value_get_integer(code_o);
 		return g_strdup_printf("Error %d: %s", code, msg ? msg : type ? type : "Unknown error");
-	} else if (e->type == json_string) {
-		return g_strdup(e->u.string.ptr);
+	} else if (json_type(e) == JSONString) {
+		return g_strdup(json_string(e));
 	}
 	return NULL;
@@ -156,18 +154,18 @@
 	if (content_type && (strstr(content_type, "application/json") ||
 	                     strstr(content_type, "text/javascript"))) {
-		json_value *js = json_parse(req->reply_body, req->body_size);
-		if (js && js->type == json_object) {
-			JSON_O_FOREACH(js, k, v){
+		JSON_Value *js = json_parse_string(req->reply_body);
+		if (js && json_type(js) == JSONObject) {
+			JSON_O_FOREACH(json_object(js), k, v){
 				if (strcmp(k, "error") == 0) {
 					error = oauth2_parse_error(v);
 				}
-				if (v->type != json_string) {
+				if (json_type(v) != JSONString) {
 					continue;
 				}
 				if (strcmp(k, "access_token") == 0) {
-					atoken = g_strdup(v->u.string.ptr);
+					atoken = g_strdup(json_string(v));
 				}
 				if (strcmp(k, "refresh_token") == 0) {
-					rtoken = g_strdup(v->u.string.ptr);
+					rtoken = g_strdup(json_string(v));
 				}
 			}
Index: lib/parson.c
===================================================================
--- lib/parson.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
+++ lib/parson.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -0,0 +1,1771 @@
+/*
+ Parson ( http://kgabis.github.com/parson/ )
+ Copyright (c) 2012 - 2014 Krzysztof Gabis
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+*/
+#ifdef _MSC_VER
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "parson.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <math.h>
+
+#define STARTING_CAPACITY         15
+#define ARRAY_MAX_CAPACITY    122880 /* 15*(2^13) */
+#define OBJECT_MAX_CAPACITY      960 /* 15*(2^6)  */
+#define MAX_NESTING               19
+#define DOUBLE_SERIALIZATION_FORMAT "%f"
+#define JINT_SERIALIZATION_FORMAT "%lld"
+
+#define SIZEOF_TOKEN(a)       (sizeof(a) - 1)
+#define SKIP_CHAR(str)        ((*str)++)
+#define SKIP_WHITESPACES(str) while (isspace(**str)) { SKIP_CHAR(str); }
+#define MAX(a, b)             ((a) > (b) ? (a) : (b))
+
+#define PARSON_MALLOC(a)     malloc(a)
+#define PARSON_FREE(a)       free((void*)(a))
+#define PARSON_REALLOC(a, b) realloc((a), (b))
+
+#define PRINT_AND_SKIP(str, to_append) str += sprintf(str, to_append);
+#define PRINTF_AND_SKIP(str, format, to_append) str += sprintf(str, format, to_append);
+
+#define IS_CONT(b) (((unsigned char)(b) & 0xC0) == 0x80) /* is utf-8 continuation byte */
+
+/* Type definitions */
+typedef union json_value_value {
+    const char  *string;
+    double       number;
+    jint         integer;
+    JSON_Object *object;
+    JSON_Array  *array;
+    int          boolean;
+    int          null;
+} JSON_Value_Value;
+
+struct json_value_t {
+    JSON_Value_Type     type;
+    JSON_Value_Value    value;
+};
+
+struct json_object_t {
+    const char **names;
+    JSON_Value **values;
+    size_t       count;
+    size_t       capacity;
+};
+
+struct json_array_t {
+    JSON_Value **items;
+    size_t       count;
+    size_t       capacity;
+};
+
+/* Various */
+static char * read_file(const char *filename);
+static void   remove_comments(char *string, const char *start_token, const char *end_token);
+static int    try_realloc(void **ptr, size_t new_size);
+static char * parson_strndup(const char *string, size_t n);
+static char * parson_strdup(const char *string);
+static int    is_utf16_hex(const unsigned char *string);
+static int    num_bytes_in_utf8_sequence(unsigned char c);
+static int    verify_utf8_sequence(const unsigned char *string, int *len);
+static int    is_valid_utf8(const char *string, size_t string_len);
+static int    is_decimal(const char *string, size_t length);
+static size_t serialization_strlen(const char *string);
+
+/* JSON Object */
+static JSON_Object * json_object_init(void);
+static JSON_Status   json_object_add(JSON_Object *object, const char *name, JSON_Value *value);
+static JSON_Status   json_object_resize(JSON_Object *object, size_t capacity);
+static JSON_Value  * json_object_nget_value(const JSON_Object *object, const char *name, size_t n);
+static void          json_object_free(JSON_Object *object);
+
+/* JSON Array */
+static JSON_Array * json_array_init(void);
+static JSON_Status  json_array_add(JSON_Array *array, JSON_Value *value);
+static JSON_Status  json_array_resize(JSON_Array *array, size_t capacity);
+static void         json_array_free(JSON_Array *array);
+
+/* JSON Value */
+static JSON_Value * json_value_init_string_no_copy(const char *string);
+
+/* Parser */
+static void         skip_quotes(const char **string);
+static int          parse_utf_16(const char **unprocessed, char **processed);
+static char*        process_string(const char *input, size_t len);
+static const char * get_quoted_string(const char **string);
+static JSON_Value * parse_object_value(const char **string, size_t nesting);
+static JSON_Value * parse_array_value(const char **string, size_t nesting);
+static JSON_Value * parse_string_value(const char **string);
+static JSON_Value * parse_boolean_value(const char **string);
+static JSON_Value * parse_number_value(const char **string);
+static JSON_Value * parse_null_value(const char **string);
+static JSON_Value * parse_value(const char **string, size_t nesting);
+
+/* Serialization */
+static size_t json_serialization_size_r(const JSON_Value *value, char *buf);
+static char * json_serialize_to_buffer_r(const JSON_Value *value, char *buf);
+static char * json_serialize_string(const char *string, char *buf);
+
+/* Various */
+static int try_realloc(void **ptr, size_t new_size) {
+    void *reallocated_ptr = NULL;
+    if (new_size == 0) {
+        return JSONFailure;
+    }
+    reallocated_ptr = PARSON_REALLOC(*ptr, new_size);
+    if (reallocated_ptr == NULL) {
+        return JSONFailure;
+    }
+    *ptr = reallocated_ptr;
+    return JSONSuccess;
+}
+
+static char * parson_strndup(const char *string, size_t n) {
+    char *output_string = (char*)PARSON_MALLOC(n + 1);
+    if (!output_string)
+        return NULL;
+    output_string[n] = '\0';
+    strncpy(output_string, string, n);
+    return output_string;
+}
+
+static char * parson_strdup(const char *string) {
+    return parson_strndup(string, strlen(string));
+}
+
+static int is_utf16_hex(const unsigned char *s) {
+    return isxdigit(s[0]) && isxdigit(s[1]) && isxdigit(s[2]) && isxdigit(s[3]);
+}
+
+static int num_bytes_in_utf8_sequence(unsigned char c) {
+    if (c == 0xC0 || c == 0xC1 || c > 0xF4 || IS_CONT(c)) {
+        return 0;
+    } else if ((c & 0x80) == 0) {    /* 0xxxxxxx */
+        return 1;
+    } else if ((c & 0xE0) == 0xC0) { /* 110xxxxx */
+        return 2;
+    } else if ((c & 0xF0) == 0xE0) { /* 1110xxxx */
+        return 3;
+    } else if ((c & 0xF8) == 0xF0) { /* 11110xxx */
+        return 4;
+    }
+    return 0; /* won't happen */
+}
+
+static int verify_utf8_sequence(const unsigned char *string, int *len) {
+    unsigned int cp = 0;
+    *len = num_bytes_in_utf8_sequence(string[0]);
+    
+    if (*len == 1) {
+        cp = string[0];
+    } else if (*len == 2 && IS_CONT(string[1])) {
+        cp = string[0] & 0x1F;
+        cp = (cp << 6) | (string[1] & 0x3F);
+    } else if (*len == 3 && IS_CONT(string[1]) && IS_CONT(string[2])) {
+        cp = ((unsigned char)string[0]) & 0xF;
+        cp = (cp << 6) | (string[1] & 0x3F);
+        cp = (cp << 6) | (string[2] & 0x3F);
+    } else if (*len == 4 && IS_CONT(string[1]) && IS_CONT(string[2]) && IS_CONT(string[3])) {
+        cp = string[0] & 0x7;
+        cp = (cp << 6) | (string[1] & 0x3F);
+        cp = (cp << 6) | (string[2] & 0x3F);
+        cp = (cp << 6) | (string[3] & 0x3F);
+    } else {
+        return 0;
+    }
+    
+    /* overlong encodings */
+    if ((cp < 0x80    && *len > 1) ||
+        (cp < 0x800   && *len > 2) ||
+        (cp < 0x10000 && *len > 3)) {
+        return 0;
+    }
+    
+    /* invalid unicode */
+    if (cp > 0x10FFFF) {
+        return 0;
+    }
+    
+    /* surrogate halves */
+    if (cp >= 0xD800 && cp <= 0xDFFF) {
+        return 0;
+    }
+    
+    return 1;
+}
+
+static int is_valid_utf8(const char *string, size_t string_len) {
+    int len = 0;
+    const char *string_end =  string + string_len;
+    while (string < string_end) {
+        if (!verify_utf8_sequence((const unsigned char*)string, &len)) {
+            return 0;
+        }
+        string += len;
+    }
+    return 1;
+}
+
+static int is_decimal(const char *string, size_t length) {
+    if (length > 1 && string[0] == '0' && string[1] != '.')
+        return 0;
+    if (length > 2 && !strncmp(string, "-0", 2) && string[2] != '.')
+        return 0;
+    while (length--)
+        if (strchr("xX", string[length]))
+            return 0;
+    return 1;
+}
+
+static size_t serialization_strlen(const char *string) {
+    size_t result = 0;
+    size_t i = 0, len = strlen(string);
+    for (i = 0; i < len; i++) {
+        if (strchr("\"\\\b\f\n\r\t", string[i])) /* must be escaped */
+            result += 2;
+        else
+            result += 1;
+    }
+    return result;
+}
+
+static char * read_file(const char * filename) {
+    FILE *fp = fopen(filename, "r");
+    size_t file_size;
+    long pos;
+    char *file_contents;
+    if (!fp)
+        return NULL;
+    fseek(fp, 0L, SEEK_END);
+    pos = ftell(fp);
+    if (pos < 0) {
+        fclose(fp);
+        return NULL;
+    }
+    file_size = pos;
+    rewind(fp);
+    file_contents = (char*)PARSON_MALLOC(sizeof(char) * (file_size + 1));
+    if (!file_contents) {
+        fclose(fp);
+        return NULL;
+    }
+    if (fread(file_contents, file_size, 1, fp) < 1) {
+        if (ferror(fp)) {
+            fclose(fp);
+            PARSON_FREE(file_contents);
+            return NULL;
+        }
+    }
+    fclose(fp);
+    file_contents[file_size] = '\0';
+    return file_contents;
+}
+
+static void remove_comments(char *string, const char *start_token, const char *end_token) {
+    int in_string = 0, escaped = 0;
+    size_t i;
+    char *ptr = NULL, current_char;
+    size_t start_token_len = strlen(start_token);
+    size_t end_token_len = strlen(end_token);
+    if (start_token_len == 0 || end_token_len == 0)
+    	return;
+    while ((current_char = *string) != '\0') {
+        if (current_char == '\\' && !escaped) {
+            escaped = 1;
+            string++;
+            continue;
+        } else if (current_char == '\"' && !escaped) {
+            in_string = !in_string;
+        } else if (!in_string && strncmp(string, start_token, start_token_len) == 0) {
+			for(i = 0; i < start_token_len; i++)
+                string[i] = ' ';
+        	string = string + start_token_len;
+            ptr = strstr(string, end_token);
+            if (!ptr)
+                return;
+            for (i = 0; i < (ptr - string) + end_token_len; i++)
+                string[i] = ' ';
+          	string = ptr + end_token_len - 1;
+        }
+        escaped = 0;
+        string++;
+    }
+}
+
+/* JSON Object */
+static JSON_Object * json_object_init(void) {
+    JSON_Object *new_obj = (JSON_Object*)PARSON_MALLOC(sizeof(JSON_Object));
+    if (!new_obj)
+        return NULL;
+    new_obj->names = (const char**)NULL;
+    new_obj->values = (JSON_Value**)NULL;
+    new_obj->capacity = 0;
+    new_obj->count = 0;
+    return new_obj;
+}
+
+static JSON_Status json_object_add(JSON_Object *object, const char *name, JSON_Value *value) {
+    size_t index = 0;
+    if (object == NULL || name == NULL || value == NULL) {
+        return JSONFailure;
+    }
+    if (object->count >= object->capacity) {
+        size_t new_capacity = MAX(object->capacity * 2, STARTING_CAPACITY);
+        if (new_capacity > OBJECT_MAX_CAPACITY)
+            return JSONFailure;
+        if (json_object_resize(object, new_capacity) == JSONFailure)
+            return JSONFailure;
+    }
+    if (json_object_get_value(object, name) != NULL)
+        return JSONFailure;
+    index = object->count;
+    object->names[index] = parson_strdup(name);
+    if (object->names[index] == NULL)
+        return JSONFailure;
+    object->values[index] = value;
+    object->count++;
+    return JSONSuccess;
+}
+
+static JSON_Status json_object_resize(JSON_Object *object, size_t capacity) {
+    if (try_realloc((void**)&object->names, capacity * sizeof(char*)) == JSONFailure)
+        return JSONFailure;
+    if (try_realloc((void**)&object->values, capacity * sizeof(JSON_Value*)) == JSONFailure)
+        return JSONFailure;
+    object->capacity = capacity;
+    return JSONSuccess;
+}
+
+static JSON_Value * json_object_nget_value(const JSON_Object *object, const char *name, size_t n) {
+    size_t i, name_length;
+    for (i = 0; i < json_object_get_count(object); i++) {
+        name_length = strlen(object->names[i]);
+        if (name_length != n)
+            continue;
+        if (strncmp(object->names[i], name, n) == 0)
+            return object->values[i];
+    }
+    return NULL;
+}
+
+static void json_object_free(JSON_Object *object) {
+    while(object->count--) {
+        PARSON_FREE(object->names[object->count]);
+        json_value_free(object->values[object->count]);
+    }
+    PARSON_FREE(object->names);
+    PARSON_FREE(object->values);
+    PARSON_FREE(object);
+}
+
+/* JSON Array */
+static JSON_Array * json_array_init(void) {
+    JSON_Array *new_array = (JSON_Array*)PARSON_MALLOC(sizeof(JSON_Array));
+    if (!new_array)
+        return NULL;
+    new_array->items = (JSON_Value**)NULL;
+    new_array->capacity = 0;
+    new_array->count = 0;
+    return new_array;
+}
+
+static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value) {
+    if (array->count >= array->capacity) {
+        size_t new_capacity = MAX(array->capacity * 2, STARTING_CAPACITY);
+        if (new_capacity > ARRAY_MAX_CAPACITY)
+            return JSONFailure;
+        if (json_array_resize(array, new_capacity) == JSONFailure)
+            return JSONFailure;
+    }
+    array->items[array->count] = value;
+    array->count++;
+    return JSONSuccess;
+}
+
+static JSON_Status json_array_resize(JSON_Array *array, size_t capacity) {
+    if (try_realloc((void**)&array->items, capacity * sizeof(JSON_Value*)) == JSONFailure)
+        return JSONFailure;
+    array->capacity = capacity;
+    return JSONSuccess;
+}
+
+static void json_array_free(JSON_Array *array) {
+    while (array->count--)
+        json_value_free(array->items[array->count]);
+    PARSON_FREE(array->items);
+    PARSON_FREE(array);
+}
+
+/* JSON Value */
+static JSON_Value * json_value_init_string_no_copy(const char *string) {
+    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
+    if (!new_value)
+        return NULL;
+    new_value->type = JSONString;
+    new_value->value.string = string;
+    return new_value;
+}
+
+/* Parser */
+static void skip_quotes(const char **string) {
+    SKIP_CHAR(string);
+    while (**string != '\"') {
+        if (**string == '\0')
+            return;
+        if (**string == '\\') {
+            SKIP_CHAR(string);
+            if (**string == '\0')
+                return;
+        }
+        SKIP_CHAR(string);
+    }
+    SKIP_CHAR(string);
+}
+
+static int parse_utf_16(const char **unprocessed, char **processed) {
+    unsigned int cp, lead, trail;
+    char *processed_ptr = *processed;
+    const char *unprocessed_ptr = *unprocessed;
+    unprocessed_ptr++; /* skips u */
+    if (!is_utf16_hex((const unsigned char*)unprocessed_ptr) || sscanf(unprocessed_ptr, "%4x", &cp) == EOF)
+            return JSONFailure;
+    if (cp < 0x80) {
+        *processed_ptr = cp; /* 0xxxxxxx */
+    } else if (cp < 0x800) {
+        *processed_ptr++ = ((cp >> 6) & 0x1F) | 0xC0; /* 110xxxxx */
+        *processed_ptr   = ((cp     ) & 0x3F) | 0x80; /* 10xxxxxx */
+    } else if (cp < 0xD800 || cp > 0xDFFF) {
+        *processed_ptr++ = ((cp >> 12) & 0x0F) | 0xE0; /* 1110xxxx */
+        *processed_ptr++ = ((cp >> 6)  & 0x3F) | 0x80; /* 10xxxxxx */
+        *processed_ptr   = ((cp     )  & 0x3F) | 0x80; /* 10xxxxxx */
+    } else if (cp >= 0xD800 && cp <= 0xDBFF) { /* lead surrogate (0xD800..0xDBFF) */
+        lead = cp;
+        unprocessed_ptr += 4; /* should always be within the buffer, otherwise previous sscanf would fail */
+        if (*unprocessed_ptr++ != '\\' || *unprocessed_ptr++ != 'u' || /* starts with \u? */
+            !is_utf16_hex((const unsigned char*)unprocessed_ptr)          ||
+            sscanf(unprocessed_ptr, "%4x", &trail) == EOF           ||
+            trail < 0xDC00 || trail > 0xDFFF) { /* valid trail surrogate? (0xDC00..0xDFFF) */
+                return JSONFailure;
+        }
+        cp = ((((lead-0xD800)&0x3FF)<<10)|((trail-0xDC00)&0x3FF))+0x010000;
+        *processed_ptr++ = (((cp >> 18) & 0x07) | 0xF0); /* 11110xxx */
+        *processed_ptr++ = (((cp >> 12) & 0x3F) | 0x80); /* 10xxxxxx */
+        *processed_ptr++ = (((cp >> 6)  & 0x3F) | 0x80); /* 10xxxxxx */
+        *processed_ptr   = (((cp     )  & 0x3F) | 0x80); /* 10xxxxxx */
+    } else { /* trail surrogate before lead surrogate */
+        return JSONFailure;
+    }
+    unprocessed_ptr += 3;
+    *processed = processed_ptr;
+    *unprocessed = unprocessed_ptr;
+    return JSONSuccess;
+}
+
+
+/* Copies and processes passed string up to supplied length.
+Example: "\u006Corem ipsum" -> lorem ipsum */
+static char* process_string(const char *input, size_t len) {
+    const char *input_ptr = input;
+    char *output = (char*)PARSON_MALLOC((len + 1) * sizeof(char));
+    char *output_ptr = output;
+    while ((*input_ptr != '\0') && (size_t)(input_ptr - input) < len) {
+        if (*input_ptr == '\\') {
+            input_ptr++;
+            switch (*input_ptr) {
+                case '\"': *output_ptr = '\"'; break;
+                case '\\': *output_ptr = '\\'; break;
+                case '/':  *output_ptr = '/';  break;
+                case 'b':  *output_ptr = '\b'; break;
+                case 'f':  *output_ptr = '\f'; break;
+                case 'n':  *output_ptr = '\n'; break;
+                case 'r':  *output_ptr = '\r'; break;
+                case 't':  *output_ptr = '\t'; break;
+                case 'u':
+                    if (parse_utf_16(&input_ptr, &output_ptr) == JSONFailure)
+                        goto error;
+                    break;
+                default:
+                    goto error;
+            }
+        } else if ((unsigned char)*input_ptr < 0x20) {
+            goto error; /* 0x00-0x19 are invalid characters for json string (http://www.ietf.org/rfc/rfc4627.txt) */
+        } else {
+            *output_ptr = *input_ptr;
+        }
+        output_ptr++;
+        input_ptr++;
+    }
+    *output_ptr = '\0';
+    if (try_realloc((void**)&output, (size_t)(output_ptr-output) + 1) == JSONFailure) /* resize to new length */
+        goto error;
+    return output;
+error:
+    free(output);
+    return NULL;
+}
+
+/* Return processed contents of a string between quotes and
+   skips passed argument to a matching quote. */
+static const char * get_quoted_string(const char **string) {
+    const char *string_start = *string;
+    size_t string_len = 0;
+    skip_quotes(string);
+    if (**string == '\0')
+        return NULL;
+    string_len = *string - string_start - 2; /* length without quotes */
+    return process_string(string_start + 1, string_len);
+}
+
+static JSON_Value * parse_value(const char **string, size_t nesting) {
+    if (nesting > MAX_NESTING)
+        return NULL;
+    SKIP_WHITESPACES(string);
+    switch (**string) {
+        case '{':
+            return parse_object_value(string, nesting + 1);
+        case '[':
+            return parse_array_value(string, nesting + 1);
+        case '\"':
+            return parse_string_value(string);
+        case 'f': case 't':
+            return parse_boolean_value(string);
+        case '-':
+        case '0': case '1': case '2': case '3': case '4':
+        case '5': case '6': case '7': case '8': case '9':
+            return parse_number_value(string);
+        case 'n':
+            return parse_null_value(string);
+        default:
+            return NULL;
+    }
+}
+
+static JSON_Value * parse_object_value(const char **string, size_t nesting) {
+    JSON_Value *output_value = json_value_init_object(), *new_value = NULL;
+    JSON_Object *output_object = json_value_get_object(output_value);
+    const char *new_key = NULL;
+    if (output_value == NULL)
+        return NULL;
+    SKIP_CHAR(string);
+    SKIP_WHITESPACES(string);
+    if (**string == '}') { /* empty object */
+        SKIP_CHAR(string);
+        return output_value;
+    }
+    while (**string != '\0') {
+        new_key = get_quoted_string(string);
+        SKIP_WHITESPACES(string);
+        if (new_key == NULL || **string != ':') {
+            json_value_free(output_value);
+            return NULL;
+        }
+        SKIP_CHAR(string);
+        new_value = parse_value(string, nesting);
+        if (new_value == NULL) {
+            PARSON_FREE(new_key);
+            json_value_free(output_value);
+            return NULL;
+        }
+        if(json_object_add(output_object, new_key, new_value) == JSONFailure) {
+            PARSON_FREE(new_key);
+            PARSON_FREE(new_value);
+            json_value_free(output_value);
+            return NULL;
+        }
+        PARSON_FREE(new_key);
+        SKIP_WHITESPACES(string);
+        if (**string != ',')
+            break;
+        SKIP_CHAR(string);
+        SKIP_WHITESPACES(string);
+    }
+    SKIP_WHITESPACES(string);
+    if (**string != '}' || /* Trim object after parsing is over */
+        json_object_resize(output_object, json_object_get_count(output_object)) == JSONFailure) {
+            json_value_free(output_value);
+            return NULL;
+    }
+    SKIP_CHAR(string);
+    return output_value;
+}
+
+static JSON_Value * parse_array_value(const char **string, size_t nesting) {
+    JSON_Value *output_value = json_value_init_array(), *new_array_value = NULL;
+    JSON_Array *output_array = json_value_get_array(output_value);
+    if (!output_value)
+        return NULL;
+    SKIP_CHAR(string);
+    SKIP_WHITESPACES(string);
+    if (**string == ']') { /* empty array */
+        SKIP_CHAR(string);
+        return output_value;
+    }
+    while (**string != '\0') {
+        new_array_value = parse_value(string, nesting);
+        if (!new_array_value) {
+            json_value_free(output_value);
+            return NULL;
+        }
+        if(json_array_add(output_array, new_array_value) == JSONFailure) {
+            PARSON_FREE(new_array_value);
+            json_value_free(output_value);
+            return NULL;
+        }
+        SKIP_WHITESPACES(string);
+        if (**string != ',')
+            break;
+        SKIP_CHAR(string);
+        SKIP_WHITESPACES(string);
+    }
+    SKIP_WHITESPACES(string);
+    if (**string != ']' || /* Trim array after parsing is over */
+        json_array_resize(output_array, json_array_get_count(output_array)) == JSONFailure) {
+            json_value_free(output_value);
+            return NULL;
+    }
+    SKIP_CHAR(string);
+    return output_value;
+}
+
+static JSON_Value * parse_string_value(const char **string) {
+    const char *new_string = get_quoted_string(string);
+    if (!new_string)
+        return NULL;
+    return json_value_init_string_no_copy(new_string);
+}
+
+static JSON_Value * parse_boolean_value(const char **string) {
+    size_t true_token_size = SIZEOF_TOKEN("true");
+    size_t false_token_size = SIZEOF_TOKEN("false");
+    if (strncmp("true", *string, true_token_size) == 0) {
+        *string += true_token_size;
+        return json_value_init_boolean(1);
+    } else if (strncmp("false", *string, false_token_size) == 0) {
+        *string += false_token_size;
+        return json_value_init_boolean(0);
+    }
+    return NULL;
+}
+
+static JSON_Value * parse_number_value(const char **string) {
+    char *jint_end, *double_end;
+    double number = strtod(*string, &double_end);
+    jint integer = strtoll(*string, &jint_end, 10);
+    JSON_Value *output_value;
+    if (double_end > jint_end || errno == ERANGE) {
+        if (is_decimal(*string, double_end - *string)) {
+            *string = double_end;
+            output_value = json_value_init_number(number);
+        } else {
+            output_value = NULL;
+        }
+    } else {
+        *string = jint_end;
+        output_value = json_value_init_integer(integer);
+    }
+    return output_value;
+}
+
+static JSON_Value * parse_null_value(const char **string) {
+    size_t token_size = SIZEOF_TOKEN("null");
+    if (strncmp("null", *string, token_size) == 0) {
+        *string += token_size;
+        return json_value_init_null();
+    }
+    return NULL;
+}
+
+/* Serialization */
+static size_t json_serialization_size_r(const JSON_Value *value, char *buf) {
+    size_t result_size = 0;
+    const char *key = NULL;
+    JSON_Value *temp_value = NULL;
+    JSON_Array *array = NULL;
+    JSON_Object *object = NULL;
+    size_t i = 0, count = 0;
+    double num = 0.0;
+    jint intnum = 0;
+    switch (json_value_get_type(value)) {
+        case JSONArray:
+            array = json_value_get_array(value);
+            count = json_array_get_count(array);
+            result_size += 2; /* [ and ] brackets */
+            if (count > 0)
+                result_size += count - 1; /* , between items */
+            for (i = 0; i < count; i++) {
+                temp_value = json_array_get_value(array, i);
+                result_size += json_serialization_size_r(temp_value, buf);
+            }
+            return result_size;
+        case JSONObject:
+            object = json_value_get_object(value);
+            count  = json_object_get_count(object);
+            result_size += 2; /* { and } brackets */
+            if (count > 0)
+                result_size += (count * 2) - 1; /* : between keys and values and , between items */
+            for (i = 0; i < count; i++) {
+                key = json_object_get_name(object, i);
+                result_size += serialization_strlen(key) + 2; /* string and quotes */
+                result_size += json_serialization_size_r(json_object_get_value(object, key), buf);
+            }
+            return result_size;
+        case JSONString:
+            return serialization_strlen(json_value_get_string(value)) + 2; /* string and quotes */
+        case JSONBoolean:
+            if (json_value_get_boolean(value))
+                return 4; /* strlen("true"); */
+            else
+                return 5; /* strlen("false"); */
+        case JSONInteger:
+            intnum = json_value_get_integer(value);
+            return (size_t)sprintf(buf, JINT_SERIALIZATION_FORMAT, intnum);
+        case JSONNumber:
+            num = json_value_get_number(value);
+            if (num == ((double)(jint)num) ) /*  check if num is integer */
+                return (size_t)sprintf(buf, JINT_SERIALIZATION_FORMAT, (jint)num);
+            return (size_t)sprintf(buf, DOUBLE_SERIALIZATION_FORMAT, num);
+        case JSONNull:
+            return 4; /* strlen("null"); */
+        case JSONError:
+            return 0;
+        default:
+            return 0;
+    }
+}
+
+char* json_serialize_to_buffer_r(const JSON_Value *value, char *buf)
+{
+    const char *key = NULL, *string = NULL;
+    JSON_Value *temp_value = NULL;
+    JSON_Array *array = NULL;
+    JSON_Object *object = NULL;
+    size_t i = 0, count = 0;
+    double num = 0.0;
+    jint intnum = 0;
+    switch (json_value_get_type(value)) {
+        case JSONArray:
+            array = json_value_get_array(value);
+            count = json_array_get_count(array);
+            PRINT_AND_SKIP(buf, "[");
+            for (i = 0; i < count; i++) {
+                temp_value = json_array_get_value(array, i);
+                buf = json_serialize_to_buffer_r(temp_value, buf);
+                if (buf == NULL)
+                    return NULL;
+                if (i < (count - 1))
+                    PRINT_AND_SKIP(buf, ",");
+            }
+            PRINT_AND_SKIP(buf, "]");
+            return buf;
+        case JSONObject:
+            object = json_value_get_object(value);
+            count  = json_object_get_count(object);
+            PRINT_AND_SKIP(buf, "{");
+            for (i = 0; i < count; i++) {
+                key = json_object_get_name(object, i);
+                buf = json_serialize_string(key, buf);
+                if (buf == NULL)
+                    return NULL;
+                PRINT_AND_SKIP(buf, ":");
+                temp_value = json_object_get_value(object, key);
+                buf = json_serialize_to_buffer_r(temp_value, buf);
+                if (buf == NULL)
+                    return NULL;
+                if (i < (count - 1))
+                    PRINT_AND_SKIP(buf, ",");
+            }
+            PRINT_AND_SKIP(buf, "}");
+            return buf;
+        case JSONString:
+            string = json_value_get_string(value);
+            buf = json_serialize_string(string, buf);
+            return buf;
+        case JSONBoolean:
+            if (json_value_get_boolean(value)) {
+                PRINT_AND_SKIP(buf, "true");
+            } else {
+                PRINT_AND_SKIP(buf, "false");
+            }
+            return buf;
+        case JSONInteger:
+            intnum = json_value_get_integer(value);
+            PRINTF_AND_SKIP(buf, JINT_SERIALIZATION_FORMAT, intnum);
+            return buf;
+        case JSONNumber:
+            num = json_value_get_number(value);
+            if (num == ((double)(int)num)) { /*  check if num is integer */
+                PRINTF_AND_SKIP(buf, "%d", (int)num);
+            } else {
+                PRINTF_AND_SKIP(buf, DOUBLE_SERIALIZATION_FORMAT, num);
+            }
+            return buf;
+        case JSONNull:
+            PRINT_AND_SKIP(buf, "null");
+            return buf;
+        case JSONError:
+            return NULL;
+        default:
+            return NULL;
+    }
+}
+
+static char * json_serialize_string(const char *string, char *buf) {
+    size_t i = 0, len = strlen(string);
+    char c = '\0';
+    PRINT_AND_SKIP(buf, "\"")
+    for (i = 0; i < len; i++) {
+        c = string[i];
+        switch (c) {
+            case '\"': PRINT_AND_SKIP(buf, "\\\"");   break;
+            case '\\': PRINT_AND_SKIP(buf, "\\\\");   break;
+            case '\b': PRINT_AND_SKIP(buf, "\\b");    break;
+            case '\f': PRINT_AND_SKIP(buf, "\\f");    break;
+            case '\n': PRINT_AND_SKIP(buf, "\\n");    break;
+            case '\r': PRINT_AND_SKIP(buf, "\\r");    break;
+            case '\t': PRINT_AND_SKIP(buf, "\\t");    break;
+            default:   PRINTF_AND_SKIP(buf, "%c", c); break;
+        }
+    }
+    PRINT_AND_SKIP(buf, "\"");
+    return buf;
+}
+
+/* Parser API */
+JSON_Value * json_parse_file(const char *filename) {
+    char *file_contents = read_file(filename);
+    JSON_Value *output_value = NULL;
+    if (file_contents == NULL)
+        return NULL;
+    output_value = json_parse_string(file_contents);
+    PARSON_FREE(file_contents);
+    return output_value;
+}
+
+JSON_Value * json_parse_file_with_comments(const char *filename) {
+    char *file_contents = read_file(filename);
+    JSON_Value *output_value = NULL;
+    if (file_contents == NULL)
+        return NULL;
+    output_value = json_parse_string_with_comments(file_contents);
+    PARSON_FREE(file_contents);
+    return output_value;
+}
+
+JSON_Value * json_parse_first(const char *string, const char **end) {
+    const char *pos;
+    JSON_Value *ret;
+
+    if (string == NULL)
+        return NULL;
+    SKIP_WHITESPACES(&string);
+    if (*string != '{' && *string != '[')
+        return NULL;
+
+    pos = string;
+    ret = parse_value(&pos, 0);
+    if (end)
+        *end = pos;
+
+    return ret;
+}
+
+JSON_Value * json_parse_string(const char *string) {
+    return json_parse_first(string, NULL);
+}
+
+JSON_Value * json_parse_string_with_comments(const char *string) {
+    JSON_Value *result = NULL;
+    char *string_mutable_copy = NULL, *string_mutable_copy_ptr = NULL;
+    string_mutable_copy = parson_strdup(string);
+    if (string_mutable_copy == NULL)
+        return NULL;
+    remove_comments(string_mutable_copy, "/*", "*/");
+    remove_comments(string_mutable_copy, "//", "\n");
+    string_mutable_copy_ptr = string_mutable_copy;
+    SKIP_WHITESPACES(&string_mutable_copy_ptr);
+    if (*string_mutable_copy_ptr != '{' && *string_mutable_copy_ptr != '[') {
+        PARSON_FREE(string_mutable_copy);
+        return NULL;
+    }
+    result = parse_value((const char**)&string_mutable_copy_ptr, 0);
+    PARSON_FREE(string_mutable_copy);
+    return result;
+}
+
+
+/* JSON Object API */
+
+JSON_Value * json_object_get_value(const JSON_Object *object, const char *name) {
+    if (object == NULL || name == NULL)
+        return NULL;
+    return json_object_nget_value(object, name, strlen(name));
+}
+
+const char * json_object_get_string(const JSON_Object *object, const char *name) {
+    return json_value_get_string(json_object_get_value(object, name));
+}
+
+jint json_object_get_integer(const JSON_Object *object, const char *name) {
+    return json_value_get_integer(json_object_get_value(object, name));
+}
+
+double json_object_get_number(const JSON_Object *object, const char *name) {
+    return json_value_get_number(json_object_get_value(object, name));
+}
+
+JSON_Object * json_object_get_object(const JSON_Object *object, const char *name) {
+    return json_value_get_object(json_object_get_value(object, name));
+}
+
+JSON_Array * json_object_get_array(const JSON_Object *object, const char *name) {
+    return json_value_get_array(json_object_get_value(object, name));
+}
+
+int json_object_get_boolean(const JSON_Object *object, const char *name) {
+    return json_value_get_boolean(json_object_get_value(object, name));
+}
+
+JSON_Value * json_object_dotget_value(const JSON_Object *object, const char *name) {
+    const char *dot_position = strchr(name, '.');
+    if (!dot_position)
+        return json_object_get_value(object, name);
+    object = json_value_get_object(json_object_nget_value(object, name, dot_position - name));
+    return json_object_dotget_value(object, dot_position + 1);
+}
+
+const char * json_object_dotget_string(const JSON_Object *object, const char *name) {
+    return json_value_get_string(json_object_dotget_value(object, name));
+}
+
+jint json_object_dotget_integer(const JSON_Object *object, const char *name) {
+    return json_value_get_integer(json_object_dotget_value(object, name));
+}
+
+double json_object_dotget_number(const JSON_Object *object, const char *name) {
+    return json_value_get_number(json_object_dotget_value(object, name));
+}
+
+JSON_Object * json_object_dotget_object(const JSON_Object *object, const char *name) {
+    return json_value_get_object(json_object_dotget_value(object, name));
+}
+
+JSON_Array * json_object_dotget_array(const JSON_Object *object, const char *name) {
+    return json_value_get_array(json_object_dotget_value(object, name));
+}
+
+int json_object_dotget_boolean(const JSON_Object *object, const char *name) {
+    return json_value_get_boolean(json_object_dotget_value(object, name));
+}
+
+size_t json_object_get_count(const JSON_Object *object) {
+    return object ? object->count : 0;
+}
+
+const char * json_object_get_name(const JSON_Object *object, size_t index) {
+    if (index >= json_object_get_count(object))
+        return NULL;
+    return object->names[index];
+}
+
+int json_object_get_tuple(const JSON_Object *object, size_t index,
+                          const char **key, const JSON_Value **value) {
+    if (index >= json_object_get_count(object))
+        return 0;
+    *key = object->names[index];
+    *value = object->values[index];
+    return 1;
+}
+
+/* JSON Array API */
+JSON_Value * json_array_get_value(const JSON_Array *array, size_t index) {
+    if (index >= json_array_get_count(array))
+        return NULL;
+    return array->items[index];
+}
+
+const char * json_array_get_string(const JSON_Array *array, size_t index) {
+    return json_value_get_string(json_array_get_value(array, index));
+}
+
+jint json_array_get_integer(const JSON_Array *array, size_t index) {
+    return json_value_get_integer(json_array_get_value(array, index));
+}
+
+double json_array_get_number(const JSON_Array *array, size_t index) {
+    return json_value_get_number(json_array_get_value(array, index));
+}
+
+JSON_Object * json_array_get_object(const JSON_Array *array, size_t index) {
+    return json_value_get_object(json_array_get_value(array, index));
+}
+
+JSON_Array * json_array_get_array(const JSON_Array *array, size_t index) {
+    return json_value_get_array(json_array_get_value(array, index));
+}
+
+int json_array_get_boolean(const JSON_Array *array, size_t index) {
+    return json_value_get_boolean(json_array_get_value(array, index));
+}
+
+size_t json_array_get_count(const JSON_Array *array) {
+    return array ? array->count : 0;
+}
+
+/* JSON Value API */
+JSON_Value_Type json_value_get_type(const JSON_Value *value) {
+    return value ? value->type : JSONError;
+}
+
+JSON_Object * json_value_get_object(const JSON_Value *value) {
+    return json_value_get_type(value) == JSONObject ? value->value.object : NULL;
+}
+
+JSON_Array * json_value_get_array(const JSON_Value *value) {
+    return json_value_get_type(value) == JSONArray ? value->value.array : NULL;
+}
+
+const char * json_value_get_string(const JSON_Value *value) {
+    return json_value_get_type(value) == JSONString ? value->value.string : NULL;
+}
+
+jint json_value_get_integer(const JSON_Value *value) {
+    if (json_value_get_type(value) == JSONNumber) {
+        return value->value.number;
+    } else if (json_value_get_type(value) == JSONInteger) {
+        return value->value.integer;
+    } else {
+        return 0;
+    }
+}
+
+double json_value_get_number(const JSON_Value *value) {
+    if (json_value_get_type(value) == JSONNumber) {
+        return value->value.number;
+    } else if (json_value_get_type(value) == JSONInteger) {
+        return value->value.integer;
+    } else {
+        return 0;
+    }
+}
+
+int json_value_get_boolean(const JSON_Value *value) {
+    return json_value_get_type(value) == JSONBoolean ? value->value.boolean : -1;
+}
+
+void json_value_free(JSON_Value *value) {
+    switch (json_value_get_type(value)) {
+        case JSONObject:
+            json_object_free(value->value.object);
+            break;
+        case JSONString:
+            if (value->value.string) { PARSON_FREE(value->value.string); }
+            break;
+        case JSONArray:
+            json_array_free(value->value.array);
+            break;
+        default:
+            break;
+    }
+    PARSON_FREE(value);
+}
+
+JSON_Value * json_value_init_object(void) {
+    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
+    if (!new_value)
+        return NULL;
+    new_value->type = JSONObject;
+    new_value->value.object = json_object_init();
+    if (!new_value->value.object) {
+        PARSON_FREE(new_value);
+        return NULL;
+    }
+    return new_value;
+}
+
+JSON_Value * json_value_init_array(void) {
+    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
+    if (!new_value)
+        return NULL;
+    new_value->type = JSONArray;
+    new_value->value.array = json_array_init();
+    if (!new_value->value.array) {
+        PARSON_FREE(new_value);
+        return NULL;
+    }
+    return new_value;
+}
+
+JSON_Value * json_value_init_string(const char *string) {
+    char *copy = NULL;
+    JSON_Value *value;
+    size_t string_len = 0;
+    if (string == NULL)
+        return NULL;
+    string_len = strlen(string);
+    if (!is_valid_utf8(string, string_len))
+        return NULL;
+    copy = parson_strndup(string, string_len);
+    if (copy == NULL)
+        return NULL;
+    value = json_value_init_string_no_copy(copy);
+    if (value == NULL)
+        PARSON_FREE(copy);
+    return value;
+}
+
+JSON_Value * json_value_init_integer(jint number) {
+    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
+    if (!new_value)
+        return NULL;
+    new_value->type = JSONInteger;
+    new_value->value.integer = number;
+    return new_value;
+}
+
+JSON_Value * json_value_init_number(double number) {
+    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
+    if (!new_value)
+        return NULL;
+    new_value->type = JSONNumber;
+    new_value->value.number = number;
+    return new_value;
+}
+
+JSON_Value * json_value_init_boolean(int boolean) {
+    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
+    if (!new_value)
+        return NULL;
+    new_value->type = JSONBoolean;
+    new_value->value.boolean = boolean ? 1 : 0;
+    return new_value;
+}
+
+JSON_Value * json_value_init_null(void) {
+    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
+    if (!new_value)
+        return NULL;
+    new_value->type = JSONNull;
+    return new_value;
+}
+
+JSON_Value * json_value_deep_copy(const JSON_Value *value) {
+    size_t i = 0;
+    JSON_Value *return_value = NULL, *temp_value_copy = NULL, *temp_value = NULL;
+    const char *temp_string = NULL, *temp_string_copy = NULL, *temp_key = NULL;
+    JSON_Array *temp_array = NULL, *temp_array_copy = NULL;
+    JSON_Object *temp_object = NULL, *temp_object_copy = NULL;
+    
+    switch (json_value_get_type(value)) {
+        case JSONArray:
+            temp_array = json_value_get_array(value);
+            return_value = json_value_init_array();
+            if (return_value == NULL)
+                return NULL;
+            temp_array_copy = json_value_get_array(return_value);
+            for (i = 0; i < json_array_get_count(temp_array); i++) {
+                temp_value = json_array_get_value(temp_array, i);
+                temp_value_copy = json_value_deep_copy(temp_value);
+                if (temp_value_copy == NULL) {
+                    json_value_free(return_value);
+                    return NULL;
+                }
+                if (json_array_add(temp_array_copy, temp_value_copy) == JSONFailure) {
+                    json_value_free(return_value);
+                    json_value_free(temp_value_copy);
+                    return NULL;
+                }
+            }
+            return return_value;
+        case JSONObject:
+            temp_object = json_value_get_object(value);
+            return_value = json_value_init_object();
+            if (return_value == NULL)
+                return NULL;
+            temp_object_copy = json_value_get_object(return_value);
+            for (i = 0; i < json_object_get_count(temp_object); i++) {
+                temp_key = json_object_get_name(temp_object, i);
+                temp_value = json_object_get_value(temp_object, temp_key);
+                temp_value_copy = json_value_deep_copy(temp_value);
+                if (temp_value_copy == NULL) {
+                    json_value_free(return_value);
+                    return NULL;
+                }
+                if (json_object_add(temp_object_copy, temp_key, temp_value_copy) == JSONFailure) {
+                    json_value_free(return_value);
+                    json_value_free(temp_value_copy);
+                    return NULL;
+                }
+            }
+            return return_value;
+        case JSONBoolean:
+            return json_value_init_boolean(json_value_get_boolean(value));
+        case JSONInteger:
+            return json_value_init_integer(json_value_get_integer(value));
+        case JSONNumber:
+            return json_value_init_number(json_value_get_number(value));
+        case JSONString:
+            temp_string = json_value_get_string(value);
+            temp_string_copy = parson_strdup(temp_string);
+            if (temp_string_copy == NULL)
+                return NULL;
+            return_value = json_value_init_string_no_copy(temp_string_copy);
+            if (return_value == NULL)
+                PARSON_FREE(temp_string_copy);
+            return return_value;
+        case JSONNull:
+            return json_value_init_null();
+        case JSONError:
+            return NULL;
+        default:
+            return NULL;
+    }
+}
+
+size_t json_serialization_size(const JSON_Value *value) {
+    char buf[1100]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */
+    return json_serialization_size_r(value, buf) + 1;
+}
+
+JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) {
+    char *serialization_result = NULL;
+    size_t needed_size_in_bytes = json_serialization_size(value);
+    if (buf_size_in_bytes < needed_size_in_bytes) {
+        return JSONFailure;
+    }
+    serialization_result = json_serialize_to_buffer_r(value, buf);
+    if(serialization_result == NULL)
+        return JSONFailure;
+    return JSONSuccess;
+}
+
+JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename) {
+    JSON_Status return_code = JSONSuccess;
+    FILE *fp = NULL;
+    char *serialized_string = json_serialize_to_string(value);
+    if (serialized_string == NULL) {
+        return JSONFailure;
+    }
+    fp = fopen (filename, "w");
+    if (fp != NULL) {
+        if (fputs (serialized_string, fp) == EOF) {
+            return_code = JSONFailure;
+        }
+        if (fclose (fp) == EOF) {
+            return_code = JSONFailure;
+        }
+    }
+    json_free_serialized_string(serialized_string);
+    return return_code;
+}
+
+char * json_serialize_to_string(const JSON_Value *value) {
+    JSON_Status serialization_result = JSONFailure;
+    size_t buf_size_bytes = json_serialization_size(value);
+    char *buf = (char*)PARSON_MALLOC(buf_size_bytes);
+    if (buf == NULL)
+        return NULL;
+    serialization_result = json_serialize_to_buffer(value, buf, buf_size_bytes);
+    if (serialization_result == JSONFailure) {
+        json_free_serialized_string(buf);
+        return NULL;
+    }
+    return buf;
+}
+
+void json_free_serialized_string(char *string) {
+    PARSON_FREE(string);
+}
+
+JSON_Status json_array_remove(JSON_Array *array, size_t ix) {
+    size_t last_element_ix = 0;
+    if (array == NULL || ix >= json_array_get_count(array)) {
+        return JSONFailure;
+    }
+    last_element_ix = json_array_get_count(array) - 1;
+    json_value_free(json_array_get_value(array, ix));
+    array->count -= 1;
+    if (ix != last_element_ix) /* Replace value with one from the end of array */
+        array->items[ix] = json_array_get_value(array, last_element_ix);
+    return JSONSuccess;
+}
+
+JSON_Status json_array_replace_value(JSON_Array *array, size_t ix, JSON_Value *value) {
+    if (array == NULL || value == NULL || ix >= json_array_get_count(array)) {
+        return JSONFailure;
+    }
+    json_value_free(json_array_get_value(array, ix));
+    array->items[ix] = value;
+    return JSONSuccess;
+}
+
+JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string) {
+    JSON_Value *value = json_value_init_string(string);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_replace_value(array, i, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_replace_integer(JSON_Array *array, size_t i, jint integer) {
+    JSON_Value *value = json_value_init_integer(integer);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_replace_value(array, i, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number) {
+    JSON_Value *value = json_value_init_number(number);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_replace_value(array, i, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean) {
+    JSON_Value *value = json_value_init_boolean(boolean);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_replace_value(array, i, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_replace_null(JSON_Array *array, size_t i) {
+    JSON_Value *value = json_value_init_null();
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_replace_value(array, i, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_clear(JSON_Array *array) {
+    size_t i = 0;
+    if (array == NULL)
+        return JSONFailure;
+    for (i = 0; i < json_array_get_count(array); i++) {
+        json_value_free(json_array_get_value(array, i));
+    }
+    array->count = 0;
+    return JSONSuccess;
+}
+
+JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value) {
+    if (array == NULL || value == NULL)
+        return JSONFailure;
+    return json_array_add(array, value);
+}
+
+JSON_Status json_array_append_string(JSON_Array *array, const char *string) {
+    JSON_Value *value = json_value_init_string(string);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_append_value(array, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_append_integer(JSON_Array *array, jint integer) {
+    JSON_Value *value = json_value_init_integer(integer);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_append_value(array, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_append_number(JSON_Array *array, double number) {
+    JSON_Value *value = json_value_init_number(number);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_append_value(array, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_append_boolean(JSON_Array *array, int boolean) {
+    JSON_Value *value = json_value_init_boolean(boolean);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_append_value(array, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_array_append_null(JSON_Array *array) {
+    JSON_Value *value = json_value_init_null();
+    if (value == NULL)
+        return JSONFailure;
+    if (json_array_append_value(array, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value) {
+    size_t i = 0;
+    JSON_Value *old_value;
+    if (object == NULL || name == NULL || value == NULL)
+        return JSONFailure;
+    old_value = json_object_get_value(object, name);
+    if (old_value != NULL) { /* free and overwrite old value */
+        json_value_free(old_value);
+        for (i = 0; i < json_object_get_count(object); i++) {
+            if (strcmp(object->names[i], name) == 0) {
+                object->values[i] = value;
+                return JSONSuccess;
+            }
+        }
+    }
+    /* add new key value pair */
+    return json_object_add(object, name, value);
+}
+
+JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string) {
+    return json_object_set_value(object, name, json_value_init_string(string));
+}
+
+JSON_Status json_object_set_integer(JSON_Object *object, const char *name, jint integer) {
+    return json_object_set_value(object, name, json_value_init_integer(integer));
+}
+
+JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number) {
+    return json_object_set_value(object, name, json_value_init_number(number));
+}
+
+JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean) {
+    return json_object_set_value(object, name, json_value_init_boolean(boolean));
+}
+
+JSON_Status json_object_set_null(JSON_Object *object, const char *name) {
+    return json_object_set_value(object, name, json_value_init_null());
+}
+
+JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value) {
+    const char *dot_pos = NULL;
+    const char *current_name = NULL;
+    JSON_Object *temp_obj = NULL;
+    JSON_Value *new_value = NULL;
+    if (value == NULL || name == NULL || value == NULL)
+        return JSONFailure;
+    dot_pos = strchr(name, '.');
+    if (dot_pos == NULL) {
+        return json_object_set_value(object, name, value);
+    } else {
+        current_name = parson_strndup(name, dot_pos - name);
+        temp_obj = json_object_get_object(object, current_name);
+        if (temp_obj == NULL) {
+            new_value = json_value_init_object();
+            if (new_value == NULL) {
+                PARSON_FREE(current_name);
+                return JSONFailure;
+            }
+            if (json_object_add(object, current_name, new_value) == JSONFailure) {
+                json_value_free(new_value);
+                PARSON_FREE(current_name);
+                return JSONFailure;
+            }
+            temp_obj = json_object_get_object(object, current_name);
+        }
+        PARSON_FREE(current_name);
+        return json_object_dotset_value(temp_obj, dot_pos + 1, value);
+    }
+}
+
+JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string) {
+    JSON_Value *value = json_value_init_string(string);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_object_dotset_value(object, name, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_object_dotset_integer(JSON_Object *object, const char *name, jint integer) {
+    JSON_Value *value = json_value_init_integer(integer);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_object_dotset_value(object, name, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number) {
+    JSON_Value *value = json_value_init_number(number);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_object_dotset_value(object, name, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean) {
+    JSON_Value *value = json_value_init_boolean(boolean);
+    if (value == NULL)
+        return JSONFailure;
+    if (json_object_dotset_value(object, name, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_object_dotset_null(JSON_Object *object, const char *name) {
+    JSON_Value *value = json_value_init_null();
+    if (value == NULL)
+        return JSONFailure;
+    if (json_object_dotset_value(object, name, value) == JSONFailure) {
+        json_value_free(value);
+        return JSONFailure;
+    }
+    return JSONSuccess;
+}
+
+JSON_Status json_object_remove(JSON_Object *object, const char *name) {
+    size_t i = 0, last_item_index = 0;
+    if (object == NULL || json_object_get_value(object, name) == NULL)
+        return JSONFailure;
+    last_item_index = json_object_get_count(object) - 1;
+    for (i = 0; i < json_object_get_count(object); i++) {
+        if (strcmp(object->names[i], name) == 0) {
+            PARSON_FREE(object->names[i]);
+            json_value_free(object->values[i]);
+            if (i != last_item_index) { /* Replace key value pair with one from the end */
+                object->names[i] = object->names[last_item_index];
+                object->values[i] = object->values[last_item_index];
+            }
+            object->count -= 1;
+            return JSONSuccess;
+        }
+    }
+    return JSONFailure; /* No execution path should end here */
+}
+
+JSON_Status json_object_dotremove(JSON_Object *object, const char *name) {
+    const char *dot_pos = strchr(name, '.');
+    const char *current_name = NULL;
+    JSON_Object *temp_obj = NULL;
+    if (dot_pos == NULL) {
+        return json_object_remove(object, name);
+    } else {
+        current_name = parson_strndup(name, dot_pos - name);
+        temp_obj = json_object_get_object(object, current_name);
+        if (temp_obj == NULL) {
+            PARSON_FREE(current_name);
+            return JSONFailure;
+        }
+        PARSON_FREE(current_name);
+        return json_object_dotremove(temp_obj, dot_pos + 1);
+    }
+}
+
+JSON_Status json_object_clear(JSON_Object *object) {
+    size_t i = 0;
+    if (object == NULL) {
+        return JSONFailure;
+    }
+    for (i = 0; i < json_object_get_count(object); i++) {        
+        PARSON_FREE(object->names[i]);
+        json_value_free(object->values[i]);
+    }
+    object->count = 0;
+    return JSONSuccess;
+}
+
+JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value) {
+    JSON_Value *temp_schema_value = NULL, *temp_value = NULL;
+    JSON_Array *schema_array = NULL, *value_array = NULL;
+    JSON_Object *schema_object = NULL, *value_object = NULL;
+    JSON_Value_Type schema_type = JSONError, value_type = JSONError;
+    const char *key = NULL;
+    size_t i = 0, count = 0;
+    if (schema == NULL || value == NULL)
+        return JSONFailure;
+    schema_type = json_value_get_type(schema);
+    value_type = json_value_get_type(value);
+    if (schema_type != value_type && schema_type != JSONNull) /* null represents all values */
+        return JSONFailure;
+    switch (schema_type) {
+        case JSONArray:
+            schema_array = json_value_get_array(schema);
+            value_array = json_value_get_array(value);
+            count = json_array_get_count(schema_array);
+            if (count == 0)
+                return JSONSuccess; /* Empty array allows all types */
+            /* Get first value from array, rest is ignored */
+            temp_schema_value = json_array_get_value(schema_array, 0);
+            for (i = 0; i < json_array_get_count(value_array); i++) {
+                temp_value = json_array_get_value(value_array, i);
+                if (json_validate(temp_schema_value, temp_value) == 0) {
+                    return JSONFailure;
+                }
+            }
+            return JSONSuccess;
+        case JSONObject:
+            schema_object = json_value_get_object(schema);
+            value_object = json_value_get_object(value);
+            count = json_object_get_count(schema_object);
+            if (count == 0)
+                return JSONSuccess; /* Empty object allows all objects */
+            else if (json_object_get_count(value_object) < count)
+                return JSONFailure; /* Tested object mustn't have less name-value pairs than schema */
+            for (i = 0; i < count; i++) {
+                key = json_object_get_name(schema_object, i);
+                temp_schema_value = json_object_get_value(schema_object, key);
+                temp_value = json_object_get_value(value_object, key);
+                if (temp_value == NULL)
+                    return JSONFailure;
+                if (json_validate(temp_schema_value, temp_value) == JSONFailure)
+                    return JSONFailure;
+            }
+            return JSONSuccess;
+        case JSONString: case JSONInteger: case JSONNumber: case JSONBoolean: case JSONNull:
+            return JSONSuccess; /* equality already tested before switch */
+        case JSONError: default:
+            return JSONFailure;
+    }
+}
+
+JSON_Status json_value_equals(const JSON_Value *a, const JSON_Value *b) {
+    JSON_Object *a_object = NULL, *b_object = NULL;
+    JSON_Array *a_array = NULL, *b_array = NULL;
+    const char *a_string = NULL, *b_string = NULL;
+    const char *key = NULL;
+    size_t a_count = 0, b_count = 0, i = 0;
+    JSON_Value_Type a_type, b_type;
+    a_type = json_value_get_type(a);
+    b_type = json_value_get_type(b);
+    if (a_type != b_type) {
+        return 0;
+    }
+    switch (a_type) {
+        case JSONArray:
+            a_array = json_value_get_array(a);
+            b_array = json_value_get_array(b);
+            a_count = json_array_get_count(a_array);
+            b_count = json_array_get_count(b_array);
+            if (a_count != b_count) {
+                return 0;
+            }
+            for (i = 0; i < a_count; i++) {
+                if (!json_value_equals(json_array_get_value(a_array, i),
+                                       json_array_get_value(b_array, i))) {
+                    return 0;
+                }
+            }
+            return 1;
+        case JSONObject:
+            a_object = json_value_get_object(a);
+            b_object = json_value_get_object(b);
+            a_count = json_object_get_count(a_object);
+            b_count = json_object_get_count(b_object);
+            if (a_count != b_count) {
+                return 0;
+            }
+            for (i = 0; i < a_count; i++) {
+                key = json_object_get_name(a_object, i);
+                if (!json_value_equals(json_object_get_value(a_object, key),
+                                       json_object_get_value(b_object, key))) {
+                    return 0;
+                }
+            }
+            return 1;
+        case JSONString:
+            a_string = json_value_get_string(a);
+            b_string = json_value_get_string(b);
+            return strcmp(a_string, b_string) == 0;
+        case JSONBoolean:
+            return json_value_get_boolean(a) == json_value_get_boolean(b);
+        case JSONInteger:
+            return json_value_get_integer(a) == json_value_get_integer(b);
+        case JSONNumber:
+            return fabs(json_value_get_number(a) - json_value_get_number(b)) < 0.000001; /* EPSILON */
+        case JSONError:
+            return 1;
+        case JSONNull:
+            return 1;
+        default:
+            return 1;
+    }
+}
+
+JSON_Value_Type json_type(const JSON_Value *value) {
+    return json_value_get_type(value);
+}
+
+JSON_Object * json_object (const JSON_Value *value) {
+    return json_value_get_object(value);
+}
+
+JSON_Array * json_array  (const JSON_Value *value) {
+    return json_value_get_array(value);
+}
+
+const char * json_string (const JSON_Value *value) {
+    return json_value_get_string(value);
+}
+
+jint json_integer (const JSON_Value *value) {
+    return json_value_get_integer(value);
+}
+
+double json_number (const JSON_Value *value) {
+    return json_value_get_number(value);
+}
+
+int json_boolean(const JSON_Value *value) {
+    return json_value_get_boolean(value);
+}
Index: lib/parson.h
===================================================================
--- lib/parson.h	(revision 7a9d9684385640d7e34060469440cc80940465d8)
+++ lib/parson.h	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -0,0 +1,222 @@
+/*
+ Parson ( http://kgabis.github.com/parson/ )
+ Copyright (c) 2012 - 2014 Krzysztof Gabis
+ 
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ 
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ 
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+*/
+
+#ifndef parson_parson_h
+#define parson_parson_h
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif    
+    
+#include <stddef.h>   /* size_t */    
+    
+/* Types and enums */
+typedef struct json_object_t JSON_Object;
+typedef struct json_array_t  JSON_Array;
+typedef struct json_value_t  JSON_Value;
+
+typedef long long jint;
+
+enum json_value_type {
+    JSONError   = -1,
+    JSONNull    = 1,
+    JSONString  = 2,
+    JSONInteger = 7,
+    JSONNumber  = 3,
+    JSONObject  = 4,
+    JSONArray   = 5,
+    JSONBoolean = 6
+};
+typedef int JSON_Value_Type;
+    
+enum json_result_t {
+    JSONSuccess = 0,
+    JSONFailure = -1
+};
+typedef int JSON_Status;
+   
+/* Parses first JSON value in a file, returns NULL in case of error */
+JSON_Value * json_parse_file(const char *filename);
+
+/* Parses first JSON value in a file and ignores comments (/ * * / and //),
+   returns NULL in case of error */
+JSON_Value * json_parse_file_with_comments(const char *filename);
+   
+/*  Like json_parse_string, but *end is set to wherever it stopped parsing. */
+JSON_Value * json_parse_first(const char *string, const char **end);
+ 
+/*  Parses first JSON value in a string, returns NULL in case of error */
+JSON_Value * json_parse_string(const char *string);
+
+/*  Parses first JSON value in a string and ignores comments (/ * * / and //),
+    returns NULL in case of error */
+JSON_Value * json_parse_string_with_comments(const char *string);
+    
+/* Serialization */
+size_t      json_serialization_size(const JSON_Value *value);
+JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes);
+JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename);
+char *      json_serialize_to_string(const JSON_Value *value);
+void        json_free_serialized_string(char *string); /* frees string from json_serialize_to_string */
+
+/* Comparing */
+int  json_value_equals(const JSON_Value *a, const JSON_Value *b);
+    
+/* Validation
+   This is *NOT* JSON Schema. It validates json by checking if object have identically 
+   named fields with matching types.
+   For example schema {"name":"", "age":0} will validate 
+   {"name":"Joe", "age":25} and {"name":"Joe", "age":25, "gender":"m"},
+   but not {"name":"Joe"} or {"name":"Joe", "age":"Cucumber"}.
+   In case of arrays, only first value in schema is checked against all values in tested array.
+   Empty objects ({}) validate all objects, empty arrays ([]) validate all arrays,
+   null validates values of every type.
+ */
+JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value);
+    
+/*
+ * JSON Object
+ */
+JSON_Value  * json_object_get_value  (const JSON_Object *object, const char *name);
+const char  * json_object_get_string (const JSON_Object *object, const char *name);
+JSON_Object * json_object_get_object (const JSON_Object *object, const char *name);
+JSON_Array  * json_object_get_array  (const JSON_Object *object, const char *name);
+jint          json_object_get_integer(const JSON_Object *object, const char *name); /* returns 0 on fail */
+double        json_object_get_number (const JSON_Object *object, const char *name); /* returns 0 on fail */
+int           json_object_get_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */
+
+/* dotget functions enable addressing values with dot notation in nested objects,
+ just like in structs or c++/java/c# objects (e.g. objectA.objectB.value).
+ Because valid names in JSON can contain dots, some values may be inaccessible
+ this way. */
+JSON_Value  * json_object_dotget_value  (const JSON_Object *object, const char *name);
+const char  * json_object_dotget_string (const JSON_Object *object, const char *name);
+JSON_Object * json_object_dotget_object (const JSON_Object *object, const char *name);
+JSON_Array  * json_object_dotget_array  (const JSON_Object *object, const char *name);
+jint          json_object_dotget_integer(const JSON_Object *object, const char *name); /* returns 0 on fail */
+double        json_object_dotget_number (const JSON_Object *object, const char *name); /* returns 0 on fail */
+int           json_object_dotget_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */
+
+/* Functions to get available names */
+size_t        json_object_get_count(const JSON_Object *object);
+const char  * json_object_get_name (const JSON_Object *object, size_t index);
+int           json_object_get_tuple(const JSON_Object *object, size_t index,
+                                    const char **key, const JSON_Value **value); /* 0 == fail */
+
+/* Creates new name-value pair or frees and replaces old value with new one. */
+JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value);
+JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string);
+JSON_Status json_object_set_integer(JSON_Object *object, const char *name, jint number);
+JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number);
+JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean);
+JSON_Status json_object_set_null(JSON_Object *object, const char *name);
+
+/* Works like dotget functions, but creates whole hierarchy if necessary. */
+JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value);
+JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string);
+JSON_Status json_object_dotset_integer(JSON_Object *object, const char *name, jint number);
+JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number);
+JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean);
+JSON_Status json_object_dotset_null(JSON_Object *object, const char *name);
+
+/* Frees and removes name-value pair */
+JSON_Status json_object_remove(JSON_Object *object, const char *name);
+
+/* Works like dotget function, but removes name-value pair only on exact match. */
+JSON_Status json_object_dotremove(JSON_Object *object, const char *key);
+
+/* Removes all name-value pairs in object */
+JSON_Status json_object_clear(JSON_Object *object);
+    
+/* 
+ *JSON Array 
+ */
+JSON_Value  * json_array_get_value  (const JSON_Array *array, size_t index);
+const char  * json_array_get_string (const JSON_Array *array, size_t index);
+JSON_Object * json_array_get_object (const JSON_Array *array, size_t index);
+JSON_Array  * json_array_get_array  (const JSON_Array *array, size_t index);
+jint          json_array_get_integer(const JSON_Array *array, size_t index); /* returns 0 on fail */
+double        json_array_get_number (const JSON_Array *array, size_t index); /* returns 0 on fail */
+int           json_array_get_boolean(const JSON_Array *array, size_t index); /* returns -1 on fail */
+size_t        json_array_get_count  (const JSON_Array *array);
+    
+/* Frees and removes value at given index, does nothing and returns JSONFailure if index doesn't exist.
+ * Order of values in array may change during execution.  */
+JSON_Status json_array_remove(JSON_Array *array, size_t i);
+
+/* Frees and removes from array value at given index and replaces it with given one.
+ * Does nothing and returns JSONFailure if index doesn't exist. */
+JSON_Status json_array_replace_value(JSON_Array *array, size_t i, JSON_Value *value);
+JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string);
+JSON_Status json_array_replace_integer(JSON_Array *array, size_t i, jint number);
+JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number);
+JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean);
+JSON_Status json_array_replace_null(JSON_Array *array, size_t i);
+
+/* Frees and removes all values from array */
+JSON_Status json_array_clear(JSON_Array *array);
+
+/* Appends new value at the end of array. */
+JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value);
+JSON_Status json_array_append_string(JSON_Array *array, const char *string);
+JSON_Status json_array_append_integer(JSON_Array *array, jint number);
+JSON_Status json_array_append_number(JSON_Array *array, double number);
+JSON_Status json_array_append_boolean(JSON_Array *array, int boolean);
+JSON_Status json_array_append_null(JSON_Array *array);
+    
+/*
+ *JSON Value
+ */
+JSON_Value * json_value_init_object (void);
+JSON_Value * json_value_init_array  (void);
+JSON_Value * json_value_init_string (const char *string); /* copies passed string */
+JSON_Value * json_value_init_integer(jint number);
+JSON_Value * json_value_init_number (double number);
+JSON_Value * json_value_init_boolean(int boolean);
+JSON_Value * json_value_init_null   (void);
+JSON_Value * json_value_deep_copy   (const JSON_Value *value);
+void         json_value_free        (JSON_Value *value);
+
+JSON_Value_Type json_value_get_type   (const JSON_Value *value);
+JSON_Object *   json_value_get_object (const JSON_Value *value);
+JSON_Array  *   json_value_get_array  (const JSON_Value *value);
+const char  *   json_value_get_string (const JSON_Value *value);
+jint            json_value_get_integer(const JSON_Value *value);
+double          json_value_get_number (const JSON_Value *value);
+int             json_value_get_boolean(const JSON_Value *value);
+
+/* Same as above, but shorter */
+JSON_Value_Type json_type   (const JSON_Value *value);
+JSON_Object *   json_object (const JSON_Value *value);
+JSON_Array  *   json_array  (const JSON_Value *value);
+const char  *   json_string (const JSON_Value *value);
+jint            json_integer(const JSON_Value *value);
+double          json_number (const JSON_Value *value);
+int             json_boolean(const JSON_Value *value);
+    
+#ifdef __cplusplus
+}
+#endif
+
+#endif
Index: protocols/account.c
===================================================================
--- protocols/account.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ protocols/account.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -27,8 +27,4 @@
 #include "bitlbee.h"
 #include "account.h"
-
-static const char* account_protocols_local[] = {
-	"gg", "whatsapp", NULL
-};
 
 static char *set_eval_nick_source(set_t *set, char *value);
@@ -469,14 +465,2 @@
 	return a->auto_reconnect_delay;
 }
-
-int protocol_account_islocal(const char* protocol)
-{
-	const char** p = account_protocols_local;
-
-	do {
-		if (strcmp(*p, protocol) == 0) {
-			return 1;
-		}
-	} while (*(++p));
-	return 0;
-}
Index: protocols/account.h
===================================================================
--- protocols/account.h	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ protocols/account.h	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -58,6 +58,4 @@
 int account_reconnect_delay(account_t *a);
 
-int protocol_account_islocal(const char* protocol);
-
 typedef enum {
 	ACC_SET_OFFLINE_ONLY = 0x02,    /* Allow changes only if the acct is offline. */
@@ -70,5 +68,5 @@
 	ACC_FLAG_STATUS_MESSAGE = 0x02, /* Supports status messages (without being away). */
 	ACC_FLAG_HANDLE_DOMAINS = 0x04, /* Contact handles need a domain portion. */
-	ACC_FLAG_LOCAL = 0x08,          /* Contact list is local. */
+	ACC_FLAG_LOCAL_CONTACTS = 0x08, /* Contact list is local. */
 	ACC_FLAG_LOCKED = 0x10,         /* Account is locked (cannot be deleted, certain settings can't changed) */
 } account_flag_t;
Index: protocols/nogaim.c
===================================================================
--- protocols/nogaim.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ protocols/nogaim.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -259,4 +259,5 @@
 	extern void twitter_initmodule();
 	extern void purple_initmodule();
+	extern void rpc_initmodule();
 
 #ifdef WITH_MSN
@@ -278,4 +279,8 @@
 #ifdef WITH_PURPLE
 	purple_initmodule();
+#endif
+
+#ifdef WITH_RPC
+	rpc_initmodule();
 #endif
 
@@ -443,10 +448,12 @@
 	}
 
-	if (ic->acc->flags & ACC_FLAG_LOCAL) {
+	if ((ic->acc->flags & ACC_FLAG_LOCAL_CONTACTS) &&
+	    !(ic->flags & OPT_LOCAL_CONTACTS_SENT) &&
+	    ic->acc->prpl->add_buddy) {
 		GHashTableIter nicks;
-		gpointer k, v;
+		gpointer handle;
 		g_hash_table_iter_init(&nicks, ic->acc->nicks);
-		while (g_hash_table_iter_next(&nicks, &k, &v)) {
-			ic->acc->prpl->add_buddy(ic, (char *) k, NULL);
+		while (g_hash_table_iter_next(&nicks, &handle, NULL)) {
+			ic->acc->prpl->add_buddy(ic, (char *) handle, NULL);
 		}
 	}
@@ -543,4 +550,13 @@
 	query_del_by_conn((irc_t *) ic->bee->ui_data, ic);
 
+	/* Throw away groupchats owned by this account. Historically this was only
+	   ever done by IM modules which is a bug. But it gives them opportunity
+	   to clean up protocol-specific bits as well so keep it that way, just
+	   do another cleanup here as a fallback. Don't want to leave any dangling
+	   pointers! */
+	while (ic->groupchats) {
+		imcb_chat_free(ic->groupchats->data);
+	}
+
 	if (!a) {
 		/* Uhm... This is very sick. */
@@ -641,4 +657,33 @@
 }
 
+/* Returns the local contacts for an IM account (based on assigned nicks).
+   Linked list should be freed, the strings themselves not! So look at it
+   like a GSList<const char*> I guess? Empty list means NULL retval (as
+   always with GSList). */
+GSList *imcb_get_local_contacts(struct im_connection *ic)
+{
+ 	GHashTableIter nicks;
+	GSList *ret = NULL;
+	
+	if (!(ic->acc->flags & ACC_FLAG_LOCAL_CONTACTS)) {
+		/* Only allow protocols that indicate local contact list
+		   support to use this function. */
+		return ret;
+	}
+	
+	g_hash_table_iter_init(&nicks, ic->acc->nicks);
+	gpointer handle;
+	while (g_hash_table_iter_next(&nicks, &handle, NULL)) {
+		ret = g_slist_prepend(ret, (char *) handle);
+	}
+	
+	/* If the protocol asked for the list, assume we won't have to send it
+	   anymore in imcb_connected(). */
+	ic->flags |= OPT_LOCAL_CONTACTS_SENT;
+	
+	return ret;
+}
+
+
 struct imcb_ask_cb_data {
 	struct im_connection *ic;
@@ -698,5 +743,7 @@
 	struct imcb_ask_cb_data *cbd = data;
 
-	cbd->ic->acc->prpl->add_buddy(cbd->ic, cbd->handle, NULL);
+	if (cbd->ic->acc->prpl->add_buddy) {
+		cbd->ic->acc->prpl->add_buddy(cbd->ic, cbd->handle, NULL);
+	}
 
 	imcb_ask_cb_free(data);
Index: protocols/nogaim.h
===================================================================
--- protocols/nogaim.h	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ protocols/nogaim.h	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -57,5 +57,10 @@
 
 /* Sharing flags between all kinds of things. I just hope I won't hit any
-   limits before 32-bit machines become extinct. ;-) */
+   limits before 32-bit machines become extinct. ;-)
+   
+   Argh! This needs to be renamed to be more clear which field they're used
+   for. As said it's currently mixed which is nonsense. Some are for the
+   im_connection flags field, some for imcb_buddy_status(), some for typing
+   notifications, and who knows what else... */
 #define OPT_LOGGED_IN   0x00000001
 #define OPT_LOGGING_OUT 0x00000002
@@ -70,4 +75,5 @@
 #define OPT_PONGS       0x00010000 /* Service sends us keep-alives */
 #define OPT_PONGED      0x00020000 /* Received a keep-alive during last interval */
+#define OPT_LOCAL_CONTACTS_SENT 0x00040000 /* Protocol already requested local contact list, so don't send it after finishing login. */
 #define OPT_SELFMESSAGE 0x00080000 /* A message sent by self from another location */
 
@@ -372,4 +378,5 @@
 G_MODULE_EXPORT void imcb_buddy_nick_change(struct im_connection *ic, const char *handle, const char *nick);
 G_MODULE_EXPORT void imcb_buddy_action_response(bee_user_t *bu, const char *action, char * const args[], void *data);
+G_MODULE_EXPORT GSList *imcb_get_local_contacts(struct im_connection *ic);
 
 G_MODULE_EXPORT void imcb_buddy_typing(struct im_connection *ic, const char *handle, guint32 flags);
Index: protocols/purple/purple.c
===================================================================
--- protocols/purple/purple.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ protocols/purple/purple.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -327,4 +327,9 @@
 	}
 	purple_accounts_remove(pa);
+	
+	/* Last, some protocols want their contact lists locally. */
+	if (strcmp(acc->prpl->name, "whatsapp") == 0 || strcmp(acc->prpl->name, "gg") == 0) {
+		acc->flags |= ACC_FLAG_LOCAL_CONTACTS;
+	}
 }
 
Index: protocols/rpc/Makefile
===================================================================
--- protocols/rpc/Makefile	(revision 7a9d9684385640d7e34060469440cc80940465d8)
+++ protocols/rpc/Makefile	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -0,0 +1,46 @@
+###########################
+## Makefile for BitlBee  ##
+##                       ##
+## Copyright 2002 Lintux ##
+###########################
+
+### DEFINITIONS
+
+-include ../../Makefile.settings
+ifdef _SRCDIR_
+_SRCDIR_ := $(_SRCDIR_)protocols/rpc/
+endif
+
+# [SH] Program variables
+objects = rpc.o
+
+LFLAGS += -r
+
+# [SH] Phony targets
+all: rpc_mod.o
+check: all
+lcov: check
+gcov: 
+	gcov *.c
+	
+.PHONY: all clean distclean
+
+clean:
+	rm -f *.o core
+
+distclean: clean
+	rm -rf .depend
+
+### MAIN PROGRAM
+
+$(objects): ../../Makefile.settings Makefile
+
+$(objects): %.o: $(_SRCDIR_)%.c
+	@echo '*' Compiling $<
+	@$(CC) -c $(CFLAGS) $(CFLAGS_BITLBEE) $< -o $@
+
+rpc_mod.o: $(objects)
+	@echo '*' Linking rpc_mod.o
+	@$(LD) $(LFLAGS) $(objects) -o rpc_mod.o
+	
+-include .depend/*.d
Index: protocols/rpc/rpc.c
===================================================================
--- protocols/rpc/rpc.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
+++ protocols/rpc/rpc.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -0,0 +1,1027 @@
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/types.h>
+#include <dirent.h>
+
+#include "bitlbee.h"
+#include "bee.h"
+#include "nogaim.h"
+#include "parson.h"
+
+#define JSON_O_FOREACH(o, k, v) \
+    const char *k; const JSON_Value *v; int __i; \
+    for (__i = 0; json_object_get_tuple(o, __i, &k, &v); __i++)
+
+static int next_rpc_id = 1;
+
+struct rpc_plugin {
+	/* Socket address of the RPC server. */
+	struct sockaddr *addr;
+	socklen_t addrlen;
+	/* Full copy of the "settings" section of the init message. This info
+	 * can only be applied later on, when an account is created (but well
+	 * before logging in). */
+	JSON_Value *settings;
+	/* Supported away states returned by the away_states() function. Since
+	 * RPC servers can't do return values, just get this info at init time.
+	 * This means the list of possible away states is static from init time
+	 * which hopefully won't be a problem. If NULL, the away_states function
+	 * will not be set on this protocol. */
+	GList *away_states;
+	/* Account flags. See account.h. Plugin lib should provide constants. */
+	int account_flags;
+};
+
+struct rpc_connection {
+	int fd;
+	char *buf;
+	int buflen;
+	GHashTable *groupchats;
+};
+
+struct rpc_groupchat {
+	int id;
+	struct groupchat *gc;
+};
+
+static JSON_Value *jsonrpc_error(int code, const char *msg) {
+	JSON_Value *ret = json_value_init_object();
+	json_object_set_null(json_object(ret), "result");
+	if (TRUE) {
+		/* Format from http://jsonrpc.org/historical/json-rpc-1-1-alt.html.
+		 * Not sure whether to use it. */
+		JSON_Value *error = json_value_init_object();
+		json_object_set_integer(json_object(error), "code", code);
+		json_object_set_string(json_object(error), "message", msg);
+		json_object_set_value(json_object(ret), "error", error);
+	} else {
+		json_object_set_string(json_object(ret), "error", msg);
+	}
+	
+	return ret;
+}
+
+// Might have liked to have this one in the library for optional values/etc.
+static void json_array_append_string_or_null(JSON_Array *array, const char *string) {
+	if (string)
+		json_array_append_string(array, string);
+	else
+		json_array_append_null(array);
+}
+
+static void json_object_set_string_or_null(JSON_Object *object, const char *key, const char *string) {
+	if (string)
+		json_object_set_string(object, key, string);
+	else
+		json_object_set_null(object, key);
+}
+
+static JSON_Value *rpc_out_new(const char *method, JSON_Array **params_) {
+	JSON_Value *rpc = json_value_init_object();
+	json_object_set_string(json_object(rpc), "method", method);
+	json_object_set_integer(json_object(rpc), "id", next_rpc_id++);
+
+	JSON_Value *params = json_value_init_array();
+	json_object_set_value(json_object(rpc), "params", params);
+
+	if (params_)
+		*params_ = json_array(params);
+
+	return rpc;
+}
+
+#define RPC_OUT_INIT(method) \
+	JSON_Array *params; \
+	JSON_Value *rpc = rpc_out_new(method, &params);
+
+/** Sends an RPC object. Takes ownership (i.e. frees it when done). */
+static gboolean rpc_send(struct im_connection *ic, JSON_Value *rpc) {
+	struct rpc_connection *rd = ic->proto_data;
+	char *buf = json_serialize_to_string(rpc);
+	int len = strlen(buf);
+	int st;
+
+	buf = g_realloc(buf, len + 3);
+	strcpy(buf + len, "\r\n");
+	len += 2;
+
+	st = write(rd->fd, buf, len);
+	g_free(buf);
+	json_value_free(rpc);
+
+	if (st != len) {
+		if (!(ic->flags & OPT_LOGGING_OUT))
+			imcb_log(ic, "Write error");
+		imc_logout(ic, TRUE);
+		return FALSE;
+	}
+
+	return TRUE;
+}
+
+static JSON_Value *rpc_ser_settings(set_t **set);
+
+static JSON_Value *rpc_ser_account(account_t *acc) {
+	JSON_Value *v = json_value_init_object();
+	JSON_Object *o = json_object(v);
+	json_object_set_string(o, "user", acc->user);
+	json_object_set_string(o, "pass", acc->pass);
+	if (acc->server)
+		json_object_set_string(o, "server", acc->server);
+	json_object_set_value(o, "settings", rpc_ser_settings(&acc->set));
+	return v;
+}
+
+static JSON_Value *rpc_ser_bee_user(bee_user_t *bu) {
+	JSON_Value *v = json_value_init_object();
+	JSON_Object *o = json_object(v);
+	json_object_set_string_or_null(o, "handle", bu->handle);
+	json_object_set_string_or_null(o, "fullname", bu->fullname);
+	json_object_set_string_or_null(o, "nick", bu->nick);
+	json_object_set_string_or_null(o, "group", bu->group ? bu->group->name : NULL);
+	json_object_set_integer(o, "flags", bu->flags);
+	json_object_set_string_or_null(o, "status", bu->status);
+	json_object_set_string_or_null(o, "status_msg", bu->status_msg);
+	json_object_set_integer(o, "login_time", bu->login_time);
+	json_object_set_integer(o, "idle_time", bu->idle_time);
+	return v;
+}
+
+static char *rpc_set_evaluator(set_t *set, char *value);
+
+static void rpc_init(account_t *acc) {
+	struct rpc_plugin *pd = acc->prpl->data;
+
+	JSON_O_FOREACH(json_object(pd->settings), name, value) {
+		JSON_Object *o = json_object(value);
+		char *defs = NULL;
+		JSON_Value *defv = json_object_get_value(o, "default");
+		if (json_type(defv) == JSONString)
+			defs = g_strdup(json_string(defv));
+		else if(json_type(defv) == JSONInteger)
+			defs = g_strdup_printf("%lld", (long long) json_integer(defv));
+		else if(json_type(defv) == JSONBoolean)
+			defs = g_strdup(json_boolean(defv) ? "true" : "false");
+		set_t *set = set_add(&acc->set, name, defs, NULL, acc);
+		g_free(defs);
+		set->flags |= json_object_get_integer(o, "flags");
+		set->eval = rpc_set_evaluator;
+		set->eval_data = o;
+		/* eval_list turns out to be a memory leak so don't implement it
+		 * for now.
+		 * Allowing a plugin to define its own evaluator is not really
+		 * possible without having BitlBee block on it responding which
+		 * I don't want to do.
+		 * Should a module want to override a user's setting, it can
+		 * use set_setstr(). */
+	}
+
+	acc->flags |= pd->account_flags;
+}
+
+set_eval rpc_type_set_eval(const set_t *set) {
+	JSON_Object *o = set->eval_data;
+	const char *type = json_object_get_string(o, "type");
+
+	set_eval type_eval = NULL;
+	if (type == NULL) {
+		/* Try to do something sane for settings that aren't ours. */
+		if (set->eval == set_eval_int || set->eval == set_eval_bool) {
+			type_eval = set->eval;
+		}
+	} else if (g_str_has_prefix(type, "int")) {
+		type_eval = set_eval_int;
+	} else if (g_str_has_prefix(type, "bool")) {
+		type_eval = set_eval_bool;
+	}
+
+	return type_eval;
+}
+
+static JSON_Value *set_make_json_value(set_eval type, const char *value) {
+	JSON_Value *ret;
+
+	if (value == NULL) {
+		ret = json_value_init_null();
+	} else if (type == set_eval_int) {
+		long long num = 0;
+		/* Evaluator already did validation so ignore retval. */
+		sscanf(value, "%lld", &num);
+		ret = json_value_init_integer(num);
+	} else if (type == set_eval_bool) {
+		ret = json_value_init_boolean(bool2int(value));
+	} else {
+		ret = json_value_init_string(value);
+	}
+	return ret;
+}
+
+static char *rpc_set_evaluator(set_t *set, char *value) {
+	set_eval type_eval = rpc_type_set_eval(set);
+	if (type_eval) {
+		char *new = type_eval(set, value);
+		if (new == SET_INVALID) {
+			return SET_INVALID;
+		}
+	}
+
+	account_t *acc = set->data;
+	if (acc->ic) {
+		/* But do send RPCs to the plugin for each changed setting so
+		 * it always has up-to-date values. */
+		RPC_OUT_INIT("set_set");
+		json_array_append_string(params, set->key);
+		json_array_append_value(params, set_make_json_value(rpc_type_set_eval(set), value));
+		rpc_send(acc->ic, rpc);
+	}
+
+	return value;
+}
+
+static JSON_Value *rpc_ser_settings(set_t **set) {
+	const set_t *s;
+	JSON_Value *ret = json_value_init_object();
+       
+	for (s = *set; s; s = s->next) {
+		JSON_Value *v = set_make_json_value(rpc_type_set_eval(s), set_value(s));
+		json_object_set_value(json_object(ret), s->key, v);
+	}
+
+	return ret;
+}
+
+static gboolean rpc_login_cb(gpointer data, gint fd, b_input_condition cond);
+static gboolean rpc_in_event(gpointer data, gint fd, b_input_condition cond);
+static JSON_Value *rpc_init_isup();
+
+static void rpc_login(account_t *acc) {
+	struct im_connection *ic = imcb_new(acc);
+	struct rpc_connection *rd = ic->proto_data = g_new0(struct rpc_connection, 1);
+	struct rpc_plugin *pd = acc->prpl->data;
+	imcb_log(ic, "Logging in via RPC server");
+	rd->fd = socket(pd->addr->sa_family, SOCK_STREAM, 0);
+	sock_make_nonblocking(rd->fd);
+	if (connect(rd->fd, pd->addr, pd->addrlen) == -1) {
+		closesocket(rd->fd);
+		imcb_error(ic, "RPC server unreachable");
+		imc_logout(ic, TRUE);
+		return;
+	}
+	ic->inpa = b_input_add(rd->fd, B_EV_IO_WRITE, rpc_login_cb, ic);
+	rd->groupchats = g_hash_table_new(g_int_hash, g_int_equal);
+}
+
+static gboolean rpc_login_cb(gpointer data, gint fd, b_input_condition cond) {
+	struct im_connection *ic = data;
+	struct rpc_connection *rd = ic->proto_data;
+
+	/* Need to repeat this since each IM connection means an actual new
+	 * RPC session. */
+	JSON_Value *init = rpc_init_isup();
+	if (!rpc_send(ic, init))
+		return FALSE;
+
+	RPC_OUT_INIT("login");
+	json_array_append_value(params, rpc_ser_account(ic->acc));
+	if (!rpc_send(ic, rpc))
+		return FALSE;
+
+	ic->inpa = b_input_add(rd->fd, B_EV_IO_READ, rpc_in_event, ic);
+
+	return FALSE;
+}
+
+static void rpc_keepalive(struct im_connection *ic) {
+	RPC_OUT_INIT("keepalive");
+	rpc_send(ic, rpc);
+}
+
+static void rpc_groupchat_free(struct groupchat *gc);
+
+static void rpc_logout(struct im_connection *ic) {
+	RPC_OUT_INIT("logout");
+	if (!rpc_send(ic, rpc))
+		return;
+
+	struct rpc_connection *rd = ic->proto_data;
+
+	GHashTableIter iter;
+	struct rpc_groupchat *rc;
+	g_hash_table_iter_init(&iter, rd->groupchats);
+	while (g_hash_table_iter_next(&iter, NULL, (gpointer*)&rc)) {
+		rpc_groupchat_free(rc->gc);
+	}
+
+	b_event_remove(ic->inpa);
+	closesocket(rd->fd);
+	g_free(rd->buf);
+	g_hash_table_destroy(rd->groupchats);
+	g_free(rd);
+}
+
+static int rpc_buddy_msg(struct im_connection *ic, char *to, char *message, int flags) {
+	RPC_OUT_INIT("buddy_msg");
+	json_array_append_string(params, to);
+	json_array_append_string(params, message);
+	json_array_append_integer(params, flags);
+	return rpc_send(ic, rpc);
+}
+
+static void rpc_set_away(struct im_connection *ic, char *state, char *message) {
+	RPC_OUT_INIT("set_away");
+	json_array_append_string_or_null(params, state);
+	json_array_append_string_or_null(params, message);
+	rpc_send(ic, rpc);
+}
+
+static int rpc_send_typing(struct im_connection *ic, char *who, int flags) {
+	RPC_OUT_INIT("send_typing");
+	json_array_append_string(params, who);
+	json_array_append_integer(params, flags);
+	return rpc_send(ic, rpc);
+}
+
+static void rpc_add_buddy(struct im_connection *ic, char *name, char *group) {
+	RPC_OUT_INIT("add_buddy");
+	json_array_append_string(params, name);
+	json_array_append_string_or_null(params, group);
+	rpc_send(ic, rpc);
+}
+
+static void rpc_remove_buddy(struct im_connection *ic, char *name, char *group) {
+	RPC_OUT_INIT("remove_buddy");
+	json_array_append_string(params, name);
+	json_array_append_string_or_null(params, group);
+	rpc_send(ic, rpc);
+}
+
+static void rpc_add_permit(struct im_connection *ic, char *who) {
+	RPC_OUT_INIT("add_permit");
+	json_array_append_string(params, who);
+	rpc_send(ic, rpc);
+}
+
+static void rpc_add_deny(struct im_connection *ic, char *who) {
+	RPC_OUT_INIT("add_deny");
+	json_array_append_string(params, who);
+	rpc_send(ic, rpc);
+}
+
+static void rpc_rem_permit(struct im_connection *ic, char *who) {
+	RPC_OUT_INIT("rem_permit");
+	json_array_append_string(params, who);
+	rpc_send(ic, rpc);
+}
+
+static void rpc_rem_deny(struct im_connection *ic, char *who) {
+	RPC_OUT_INIT("rem_deny");
+	json_array_append_string(params, who);
+	rpc_send(ic, rpc);
+}
+
+static void rpc_get_info(struct im_connection *ic, char *who) {
+	RPC_OUT_INIT("get_info");
+	json_array_append_string(params, who);
+	rpc_send(ic, rpc);
+}
+
+static void rpc_chat_invite(struct groupchat *gc, char *who, char *message) {
+	RPC_OUT_INIT("chat_invite");
+	struct rpc_groupchat *rc = gc->data;
+	json_array_append_integer(params, rc->id);
+	json_array_append_string(params, who);
+	json_array_append_string_or_null(params, message);
+	rpc_send(gc->ic, rpc);
+}
+
+static void rpc_chat_kick(struct groupchat *gc, char *who, const char *message) {
+	RPC_OUT_INIT("chat_kick");
+	struct rpc_groupchat *rc = gc->data;
+	json_array_append_integer(params, rc->id);
+	json_array_append_string(params, who);
+	json_array_append_string_or_null(params, message);
+	rpc_send(gc->ic, rpc);
+}
+
+static void rpc_chat_leave(struct groupchat *gc) {
+	RPC_OUT_INIT("chat_leave");
+	struct rpc_groupchat *rc = gc->data;
+	json_array_append_integer(params, rc->id);
+	rpc_send(gc->ic, rpc);
+
+	struct rpc_connection *rd = gc->ic->proto_data;
+	g_hash_table_remove(rd->groupchats, &rc->id);
+	rpc_groupchat_free(gc);
+}
+
+static void rpc_chat_msg(struct groupchat *gc, char *msg, int flags) {
+	RPC_OUT_INIT("chat_msg");	
+	struct rpc_groupchat *rc = gc->data;
+	json_array_append_integer(params, rc->id);
+	json_array_append_string(params, msg);
+	json_array_append_integer(params, flags);
+	rpc_send(gc->ic, rpc);
+}
+
+static struct rpc_groupchat *rpc_groupchat_new(struct im_connection *ic, const char *handle) {
+	struct rpc_connection *rd = ic->proto_data;
+	struct groupchat *gc = imcb_chat_new(ic, handle);
+	struct rpc_groupchat *rc = gc->data = g_new0(struct rpc_groupchat, 1);
+	rc->id = next_rpc_id++;
+	rc->gc = gc;
+	g_hash_table_insert(rd->groupchats, &rc->id, rc);
+	return rc;  // TODO: RETVAL HERE AND BELOW
+}
+
+static struct rpc_groupchat *rpc_groupchat_by_id(struct im_connection *ic, int id) {
+	struct rpc_connection *rd = ic->proto_data;
+	struct rpc_groupchat *rc = g_hash_table_lookup(rd->groupchats, &id);
+
+	return rc;
+}
+
+/* When calling this, also make sure the element gets removes from
+   rpc_connection->groupchat. This function doesn't do that because it gets
+   called from within an iterator. */
+static void rpc_groupchat_free(struct groupchat *gc) {
+	g_free(gc->data);
+	imcb_chat_free(gc);
+}
+
+/* Boilerplate for all incoming RPCs (where groupchat is identified using
+ * numeric ID). */
+#define SET_GROUPCHAT(rc) \
+	do { \
+		rc = rpc_groupchat_by_id(ic, json_array_get_integer(params, 0)); \
+		if (rc == NULL) \
+			return jsonrpc_error(ENOENT, "No groupchat with that id."); \
+	} while (0)
+
+static struct groupchat *rpc_chat_with(struct im_connection *ic, char *who) {
+	RPC_OUT_INIT("chat_with");
+	struct rpc_groupchat *rc = rpc_groupchat_new(ic, who);
+	json_array_append_integer(params, rc->id);
+	json_array_append_string(params, who);
+	rpc_send(ic, rpc);
+
+	return rc->gc; 
+}
+
+static struct groupchat *rpc_chat_join(struct im_connection *ic, const char *room, const char *nick,
+                                       const char *password, set_t **sets) {
+	RPC_OUT_INIT("chat_join");
+	struct rpc_groupchat *rc = rpc_groupchat_new(ic, room);
+	json_array_append_integer(params, rc->id);
+	json_array_append_string(params, room);
+	json_array_append_string_or_null(params, nick);
+	json_array_append_string_or_null(params, password);
+	json_array_append_value(params, rpc_ser_settings(sets));
+	rpc_send(ic, rpc);
+
+	return rc->gc;
+}
+
+static void rpc_chat_topic(struct groupchat *gc, char *topic) {
+	RPC_OUT_INIT("chat_topic");
+	struct rpc_groupchat *rc = gc->data;
+	json_array_append_integer(params, rc->id);
+	json_array_append_string(params, topic);
+	rpc_send(gc->ic, rpc);
+}
+
+static GList *rpc_away_states(struct im_connection *ic) {
+	struct rpc_plugin *pd = ic->acc->prpl->data;
+	return pd->away_states;
+}
+
+static JSON_Value *rpc_cmd_in(struct im_connection *ic, const char *cmd, JSON_Array *params);
+
+static gboolean rpc_in(struct im_connection *ic, JSON_Object *rpc) {
+	const char *cmd = json_object_get_string(rpc, "method");
+	JSON_Value *id = json_object_get_value(rpc, "id");
+	JSON_Value *error = json_object_get_value(rpc, "error");
+	JSON_Array *params = json_object_get_array(rpc, "params");
+
+	/* Removed checks for result/error/etc. as it's all too free-form and
+	 * at least for now this code is not going to care about retvals as
+	 * they come in late anyway. */
+	if (!id) {
+		imcb_log(ic, "Received invalid JSON-RPC object.");
+		imc_logout(ic, TRUE);
+		return FALSE;
+	}
+
+	if (cmd) {
+		JSON_Value *resp = rpc_cmd_in(ic, cmd, params);
+		if (!resp) {
+			resp = json_value_init_object();
+			json_object_set_boolean(json_object(resp), "result", TRUE);
+		}
+		json_object_set_value(json_object(resp), "id", json_value_deep_copy(id));
+		return rpc_send(ic, resp);
+	} else if (error && json_type(error) != JSONNull) {
+		char *error_str = json_serialize_to_string(error);
+		/* Maybe sanitise/truncate? Though really that should be done at
+		 * a different layer. */
+		imcb_error(ic, "RPC Error: %s", error_str);
+		g_free(error_str);
+	}
+
+	return TRUE;
+}
+
+static gboolean rpc_in_event(gpointer data, gint fd, b_input_condition cond) {
+	struct im_connection *ic = data;
+	struct rpc_connection *rd = ic->proto_data;
+	char buf[2048];
+	int st;
+
+	while ((st = read(rd->fd, buf, sizeof(buf))) > 0) {
+		rd->buf = g_realloc(rd->buf, rd->buflen + st + 1);
+		memcpy(rd->buf + rd->buflen, buf, st);
+		rd->buflen += st;
+	}
+
+	if (st == 0 || (st == -1 && !(sockerr_again() || errno == EAGAIN))) {
+		imcb_log(ic, "Lost RPC connection");
+		imc_logout(ic, TRUE);
+		return FALSE;
+	}
+	rd->buf[rd->buflen] = '\0';
+
+	JSON_Value *parsed;
+	const char *end;
+	while ((parsed = json_parse_first(rd->buf, &end))) {
+		st = rpc_in(ic, json_object(parsed));
+		json_value_free(parsed);
+
+		if (!st)
+			return FALSE;
+
+		if (end == rd->buf + rd->buflen) {
+			g_free(rd->buf);
+			rd->buf = NULL;
+		} else {
+			int newlen = rd->buf + rd->buflen - end;
+			char new[newlen];
+			memcpy(new, end, newlen);
+			rd->buf = g_realloc(rd->buf, newlen + 1);
+			memcpy(rd->buf, new, newlen);
+			rd->buflen = newlen;
+			rd->buf[rd->buflen] = '\0';
+		}
+	}
+
+	return TRUE;
+}
+
+static JSON_Value *rpc_imcb_log(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*, const char*, ...) = func_;
+	func(ic, "%s", json_array_get_string(params, 0));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_connected(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*) = func_;
+	func(ic);
+	return NULL;
+}
+
+static JSON_Value *rpc_imc_logout(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*, gboolean) = func_;
+	func(ic, json_array_get_boolean(params, 0));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_add_buddy(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*, const char*, const char*) = func_;
+	func(ic, json_array_get_string(params, 0), json_array_get_string(params, 1));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_buddy_status(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*, const char*, int, const char*, const char*) = func_;
+	func(ic, json_array_get_string(params, 0), json_array_get_integer(params, 1),
+	         json_array_get_string(params, 2), json_array_get_string(params, 3));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_buddy_times(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*, const char*, int, int) = func_;
+	func(ic, json_array_get_string(params, 0), json_array_get_integer(params, 1),
+	         json_array_get_integer(params, 2));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_buddy_msg(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*, const char*, const char*, int, int) = func_;
+	func(ic, json_array_get_string(params, 0), json_array_get_string(params, 1),
+	         json_array_get_integer(params, 2), json_array_get_integer(params, 3));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_buddy_typing(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct im_connection*, const char*, int) = func_;
+	func(ic, (char*) json_array_get_string(params, 0), json_array_get_integer(params, 1));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_get_local_contacts(struct im_connection *ic, void *func_, JSON_Array *params) {
+	JSON_Value *resp = json_value_init_object();
+	JSON_Value *arr = json_value_init_array();
+	GSList *contacts = imcb_get_local_contacts(ic);
+	GSList *c;
+	for (c = contacts; c; c = c->next) {
+		json_array_append_string(json_array(arr), (const char*) c->data);
+	}
+	g_slist_free(contacts);
+	json_object_set_value(json_object(resp), "result", arr);
+	return resp;
+}
+
+static JSON_Value *rpc_imcb_chat_new(struct im_connection *ic, void *func_, JSON_Array *params) {
+	struct rpc_groupchat *rc = rpc_groupchat_new(ic, json_array_get_string(params, 0));
+	JSON_Value *resp = json_value_init_object();
+	json_object_set_integer(json_object(resp), "result", rc->id);
+	return resp;
+}
+
+static JSON_Value *rpc_imcb_chat_name_hint(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct groupchat*, const char*) = func_;
+	struct rpc_groupchat *rc;
+	SET_GROUPCHAT(rc);
+	func(rc->gc, json_array_get_string(params, 1));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_chat_msg(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct groupchat*, const char*, const char*, guint32, time_t) = func_;
+	struct rpc_groupchat *rc;
+	SET_GROUPCHAT(rc);
+	func(rc->gc, json_array_get_string(params, 1), json_array_get_string(params, 2),
+	     json_array_get_integer(params, 3), json_array_get_integer(params, 4));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_chat_log(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct groupchat*, const char*, ...) = func_;
+	struct rpc_groupchat *rc;
+	SET_GROUPCHAT(rc);
+	func(rc->gc, "%s", json_array_get_string(params, 1));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_chat_topic(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct groupchat*, const char*, const char*, time_t) = func_;
+	struct rpc_groupchat *rc;
+	SET_GROUPCHAT(rc);
+	func(rc->gc, json_array_get_string(params, 1), json_array_get_string(params, 2),
+	     json_array_get_integer(params, 3));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_chat_remove_buddy(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct groupchat*, const char*, const char*) = func_;
+	struct rpc_groupchat *rc;
+	SET_GROUPCHAT(rc);
+	func(rc->gc, json_array_get_string(params, 1), json_array_get_string(params, 2));
+	return NULL;
+}
+
+static JSON_Value *rpc_imcb_chat_invite(struct im_connection *ic, void *func_, JSON_Array *params) {
+	void (*func)(struct groupchat*, const char*, const char*, const char*) = func_;
+	struct rpc_groupchat *rc;
+	SET_GROUPCHAT(rc);
+	func(rc->gc, json_array_get_string(params, 1), json_array_get_string(params, 2),
+	     json_array_get_string(params, 3));
+	return NULL;
+}
+
+static JSON_Value *rpc_set_getstr(struct im_connection *ic, void *func_, JSON_Array *params) {
+	char *rets = set_getstr(&ic->acc->set, json_array_get_string(params, 0));
+	JSON_Value *ret = json_value_init_object();
+	if (rets)
+		json_object_set_string(json_object(ret), "result", rets);
+	else
+		json_object_set_null(json_object(ret), "result");
+	return ret;
+}
+
+static JSON_Value *rpc_set_setstr(struct im_connection *ic, void *func_, JSON_Array *params) {
+	/* Sadly use of const is very poor in BitlBee. :-( */
+	char *newval = g_strdup(json_array_get_string(params, 1));
+	set_setstr(&ic->acc->set, json_array_get_string(params, 0), newval);
+	g_free(newval);
+	return rpc_set_getstr(ic, func_, params);
+}
+
+static JSON_Value *rpc_set_reset(struct im_connection *ic, void *func_, JSON_Array *params) {
+	set_reset(&ic->acc->set, json_array_get_string(params, 0));
+	return rpc_set_getstr(ic, func_, params);
+}
+
+static JSON_Value *rpc_bee_user_by_handle(struct im_connection *ic, void *func_, JSON_Array *params) {
+	bee_user_t *bu = bee_user_by_handle(ic->bee, ic, json_array_get_string(params, 0));
+	JSON_Value *ret = json_value_init_object();
+	if (bu)
+		json_object_set_value(json_object(ret), "result", rpc_ser_bee_user(bu));
+	else
+		json_object_set_value(json_object(ret), "error", jsonrpc_error(ENOENT, "Contact not found"));
+	return ret;
+}
+
+struct rpc_in_method {
+	char *name;
+	void *func;
+	JSON_Value* (* wfunc) (struct im_connection *ic, void *cmd, JSON_Array *params);
+	char args[8];
+};
+
+static const struct rpc_in_method methods[] = {
+	/* All these RPCs are equivalent of BitlBee C functions but with the
+	 * struct im_connection* removed as this is in the object context. */
+	{ "imcb_log", imcb_log, rpc_imcb_log, "s" },
+	{ "imcb_error", imcb_error, rpc_imcb_log, "s" },
+	{ "imcb_connected", imcb_connected, rpc_imcb_connected, "" },
+	{ "imc_logout", imc_logout, rpc_imc_logout, "b" },
+	{ "imcb_add_buddy", imcb_add_buddy, rpc_imcb_add_buddy, "ss" },
+	{ "imcb_remove_buddy", imcb_remove_buddy, rpc_imcb_add_buddy, "ss" },
+	{ "imcb_rename_buddy", imcb_rename_buddy, rpc_imcb_add_buddy, "ss" },
+	{ "imcb_buddy_nick_hint", imcb_buddy_nick_hint, rpc_imcb_add_buddy, "ss" },
+	{ "imcb_buddy_status", imcb_buddy_status, rpc_imcb_buddy_status, "siss" },
+	{ "imcb_buddy_status_msg", imcb_buddy_status_msg, rpc_imcb_add_buddy, "ss" },
+	{ "imcb_buddy_times", imcb_buddy_times, rpc_imcb_buddy_times, "sii" },
+	{ "imcb_buddy_msg", imcb_buddy_msg, rpc_imcb_buddy_msg, "ssii" },
+	{ "imcb_buddy_typing", imcb_buddy_typing, rpc_imcb_buddy_typing, "si" },
+	{ "imcb_get_local_contacts", NULL, rpc_imcb_get_local_contacts, "" },
+	{ "imcb_chat_new", NULL, rpc_imcb_chat_new, "s" },
+	
+	/* RPCs below are equivalent, but with the struct groupchat* replaced
+	 * with the numeric id of the chat. */
+	{ "imcb_chat_name_hint", imcb_chat_name_hint, rpc_imcb_chat_name_hint, "is" },
+	{ "imcb_chat_msg", imcb_chat_msg, rpc_imcb_chat_msg, "issii" },
+	{ "imcb_chat_log", imcb_chat_log, rpc_imcb_chat_log, "is" },
+	{ "imcb_chat_topic", imcb_chat_topic, rpc_imcb_chat_topic, "issi" },
+	{ "imcb_chat_add_buddy", imcb_chat_add_buddy, rpc_imcb_chat_name_hint, "is" },
+	{ "imcb_chat_remove_buddy", imcb_chat_remove_buddy, rpc_imcb_chat_remove_buddy, "iss" },
+	{ "imcb_chat_invite", imcb_chat_invite, rpc_imcb_chat_invite, "isss" },
+
+	/* These are not imcb* functions but should still be exported. */
+	/* Setting functions. Starting with just providing access to account
+	 * settings. See later whether access to chat/chan settings is necessary.
+	 * All of these will return the (new) value of given setting. */
+	{ "set_getstr", NULL, rpc_set_getstr, "s" },
+	{ "set_setstr", NULL, rpc_set_setstr, "ss" },
+	{ "set_reset", NULL, rpc_set_reset, "s" },
+	
+	{ "bee_user_by_handle", NULL, rpc_bee_user_by_handle, "s" },
+
+	{ NULL },
+};
+
+static JSON_Value *rpc_cmd_in(struct im_connection *ic, const char *cmd, JSON_Array *params) {
+	int i;
+
+	for (i = 0; methods[i].name; i++) {
+		if (strcmp(cmd, methods[i].name) == 0) {
+			if (json_array_get_count(params) != strlen(methods[i].args)) {
+				imcb_error(ic, "Invalid argument count to method %s: %d, wanted %zd", cmd, (int) json_array_get_count(params), strlen(methods[i].args));
+				return jsonrpc_error(E2BIG, "Invalid integer of arguments");
+			}
+			int j;
+			for (j = 0; methods[i].args[j]; j++) {
+				JSON_Value_Type type = json_value_get_type(json_array_get_value(params, j));
+				gboolean ok = FALSE;
+				switch (methods[i].args[j]) {
+				case 's':
+					ok = type == JSONString || type == JSONNull;
+					break;
+				case 'i':
+					ok = type == JSONInteger;
+					break;
+				case 'o':
+					ok = type == JSONObject;
+					break;
+				case 'a':
+					ok = type == JSONArray;
+					break;
+				case 'b':
+					ok = type == JSONBoolean;
+					break;
+				}
+				if (!ok) {
+					// This error sucks, but just get your types right!
+					imcb_error(ic, "Invalid argument type, %s parameter %d: %d not %c", cmd, j, type, methods[i].args[j]);
+					return jsonrpc_error(EINVAL, "Invalid argument type");
+				}
+			}
+			return methods[i].wfunc(ic, methods[i].func, params);
+		}
+	}
+	return jsonrpc_error(ENOSYS, "Function not implemented");
+}
+
+#define RPC_ADD_FUNC(func) \
+	ret->func = rpc_ ## func
+#define RPC_ADD_OPT_FUNC(func) \
+	if (g_hash_table_lookup(methods, #func)) \
+		RPC_ADD_FUNC(func)
+
+static JSON_Value *rpc_init_isup() {
+	int i;
+
+	RPC_OUT_INIT("init");
+	JSON_Value *d = json_value_init_object();
+	json_object_set_string(json_object(d), "version_str", BITLBEE_VERSION);
+	json_object_set_integer(json_object(d), "version", BITLBEE_VERSION_CODE);
+	
+	JSON_Value *ml = json_value_init_array();
+	for (i = 0; methods[i].name; i++) {
+		json_array_append_string(json_array(ml), methods[i].name);
+	}
+	json_object_set_value(json_object(d), "method_list", ml);
+	json_array_append_value(params, d);
+
+	return rpc;
+}
+
+gboolean rpc_initmodule_sock(struct sockaddr *address, socklen_t addrlen) {
+	int st, fd, i;
+
+	fd = socket(address->sa_family, SOCK_STREAM, 0);
+	if (fd == -1 || connect(fd, address, addrlen) == -1) {
+		log_message(LOGLVL_WARNING, "Failed to connect to RPC server: %s", strerror(errno));
+		if (fd != -1)
+			closesocket(fd);
+		return FALSE;
+	}
+
+	JSON_Value *rpc = rpc_init_isup();
+	char *s = json_serialize_to_string(rpc);
+	json_value_free(rpc);
+
+	int len = strlen(s);
+	s = g_realloc(s, len + 3);
+	strcpy(s + len, "\r\n");
+	len += 2;
+
+	if ((st = write(fd, s, len)) != len) {
+		log_message(LOGLVL_WARNING, "Error while writing to RPC server: %s", strerror(errno));
+		return FALSE;
+	}
+	g_free(s);
+
+	char *resp = NULL;
+	int buflen = 4096, resplen = 0;
+	JSON_Value *parsed;
+	do {
+		fd_set rfds;
+		struct timeval to;
+
+		FD_ZERO(&rfds);
+		FD_SET(fd, &rfds);
+		to.tv_sec = 1;
+		to.tv_usec = 0;
+		st = select(fd + 1, &rfds, NULL, NULL, &to);
+
+		if (st == 0) {
+			log_message(LOGLVL_WARNING, "Error while reading from RPC server: %s", strerror(errno));
+			closesocket(fd);
+			return FALSE;
+		}
+		
+		if (resplen >= buflen)
+			buflen *= 2;
+		resp = g_realloc(resp, buflen + 1);
+		st = read(fd, resp + resplen, buflen - resplen);
+		if (st == -1) {
+			if (sockerr_again())
+				continue;
+			log_message(LOGLVL_WARNING, "Error while reading from RPC server: %s", strerror(errno));
+			closesocket(fd);
+			return FALSE;
+		}
+		resplen += st;
+		resp[resplen] = '\0';
+	}
+	while (!(parsed = json_parse_string(resp)));
+	closesocket(fd);
+
+	JSON_Object *isup = json_object_get_object(json_object(parsed), "result");
+	if (isup == NULL) {
+		log_message(LOGLVL_WARNING, "Error while parsing RPC server response");
+		return FALSE;
+	}
+
+	struct prpl *ret = g_new0(struct prpl, 1);
+	struct rpc_plugin *proto_data = g_new0(struct rpc_plugin, 1);
+	proto_data->addr = g_memdup(address, addrlen);
+	proto_data->addrlen = addrlen;
+	ret->name = g_strdup(json_object_get_string(isup, "name"));
+	ret->data = proto_data;
+
+	proto_data->account_flags = json_object_get_integer(isup, "account_flags");
+
+	/* Keep a full copy of the settings list, we can only use it when we
+	 * have an account to work on. */
+	JSON_Value *settings = json_object_get_value(isup, "settings");
+	if (json_type(settings) == JSONObject)
+		proto_data->settings = json_value_deep_copy(settings);
+
+	JSON_Array *aways_a = json_object_get_array(isup, "away_state_list");
+	for (i = 0; i < json_array_get_count(aways_a); ++i) {
+		JSON_Value *state = json_array_get_value(aways_a, i);
+		if (json_type(state) == JSONString)
+			proto_data->away_states =
+				g_list_append(proto_data->away_states,
+					      g_strdup(json_string(state)));
+	}
+
+	JSON_Array *methods_a = json_object_get_array(isup, "method_list");
+	GHashTable *methods = g_hash_table_new(g_str_hash, g_str_equal);
+	for (i = 0; i < json_array_get_count(methods_a); i++) {
+		gpointer func = (void*) json_array_get_string(methods_a, i);
+		g_hash_table_replace(methods, func, func);
+	}
+
+	ret->init = rpc_init;
+	RPC_ADD_FUNC(login);
+	RPC_ADD_OPT_FUNC(keepalive);
+	RPC_ADD_FUNC(logout);
+	RPC_ADD_FUNC(buddy_msg);
+	RPC_ADD_OPT_FUNC(set_away);
+	RPC_ADD_OPT_FUNC(send_typing);
+	RPC_ADD_OPT_FUNC(add_buddy);
+	RPC_ADD_OPT_FUNC(remove_buddy);
+	RPC_ADD_OPT_FUNC(add_permit);
+	RPC_ADD_OPT_FUNC(add_deny);
+	RPC_ADD_OPT_FUNC(rem_permit);
+	RPC_ADD_OPT_FUNC(rem_deny);
+	RPC_ADD_OPT_FUNC(get_info);
+	RPC_ADD_OPT_FUNC(chat_invite);
+	RPC_ADD_OPT_FUNC(chat_kick);
+	RPC_ADD_OPT_FUNC(chat_leave);
+	RPC_ADD_OPT_FUNC(chat_msg);
+	RPC_ADD_OPT_FUNC(chat_with);
+	RPC_ADD_OPT_FUNC(chat_join);
+	RPC_ADD_OPT_FUNC(chat_topic);
+	if (proto_data->away_states)
+		ret->away_states = rpc_away_states;
+	
+	g_hash_table_destroy(methods);
+
+	// TODO: Property for a few standard nickcmp implementations.
+	ret->handle_cmp = g_ascii_strcasecmp;
+	
+	register_protocol(ret);
+
+	return TRUE;
+}
+
+/* YA RLY :-/ */
+#ifndef UNIX_PATH_MAX
+struct sockaddr_un sizecheck;
+#define UNIX_PATH_MAX sizeof(sizecheck.sun_path)
+#endif
+
+void rpc_initmodule() {
+	DIR *pdir = opendir(RPCPLUGINDIR);
+	struct dirent *de;
+
+	if (!pdir)
+		return;
+
+	while ((de = readdir(pdir))) {
+		if (de->d_type != DT_SOCK && de->d_type != DT_UNKNOWN)
+			continue;
+
+		char *fn = g_build_filename(RPCPLUGINDIR, de->d_name, NULL);
+		struct sockaddr_un su;
+
+		strncpy(su.sun_path, fn, UNIX_PATH_MAX);
+
+#if 0
+		struct stat fdata;
+		if (stat(fn, &fdata) == -1) {
+			log_message(LOGLVL_WARNING, "Could not stat %s: %s", fn, strerror(errno));
+			g_free(fn);
+			continue;
+		}
+		/* For now just skip anything that is not a Unix domain socket. */
+		if (!S_ISSOCK(fdata.st_mode))
+			continue;
+#endif
+
+		su.sun_path[UNIX_PATH_MAX-1] = '\0';
+		su.sun_family = AF_UNIX;
+		gboolean st = rpc_initmodule_sock((struct sockaddr*) &su, sizeof(su));
+		g_free(fn);
+		if (!st)
+			log_message(LOGLVL_WARNING, "Failed to register protocol %s", fn);
+		/* Idea: Also support textfiles containing a host:port tuple to
+		 * connect to. Not that remote RPC'ing would be a great idea,
+		 * but maybe some jsonrpc libs don't support Unix domain sockets. */
+	}
+	closedir(pdir);
+}
+
Index: protocols/twitter/twitter_lib.c
===================================================================
--- protocols/twitter/twitter_lib.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ protocols/twitter/twitter_lib.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -36,5 +36,5 @@
 #include "base64.h"
 #include "twitter_lib.h"
-#include "json_util.h"
+#include "parson.h"
 #include <ctype.h>
 #include <errno.h>
@@ -64,4 +64,8 @@
 	gboolean from_filter;
 };
+
+#define JSON_O_FOREACH(o, k, v) \
+    const char *k; const JSON_Value *v; int __i; \
+    for (__i = 0; json_object_get_tuple(o, __i, &k, &v); __i++)
 
 /**
@@ -166,5 +170,5 @@
 {
 	static char *ret = NULL;
-	json_value *root, *err;
+	JSON_Value *root, *err;
 
 	g_free(ret);
@@ -172,9 +176,10 @@
 
 	if (req->body_size > 0) {
-		root = json_parse(req->reply_body, req->body_size);
-		err = json_o_get(root, "errors");
-		if (err && err->type == json_array && (err = err->u.array.values[0]) &&
-		    err->type == json_object) {
-			const char *msg = json_o_str(err, "message");
+		root = json_parse_string(req->reply_body);
+		err = json_object_get_value(json_object(root), "errors");
+		if (err && json_type(err) == JSONArray &&
+		    (err = json_array_get_value(json_array(err), 0)) &&
+		    json_type(err) == JSONObject) {
+			const char *msg = json_object_get_string(json_object(err), "message");
 			if (msg) {
 				ret = g_strdup_printf("%s (%s)", req->status_string, msg);
@@ -189,10 +194,10 @@
 /* WATCH OUT: This function might or might not destroy your connection.
    Sub-optimal indeed, but just be careful when this returns NULL! */
-static json_value *twitter_parse_response(struct im_connection *ic, struct http_request *req)
+static JSON_Value *twitter_parse_response(struct im_connection *ic, struct http_request *req)
 {
 	gboolean logging_in = !(ic->flags & OPT_LOGGED_IN);
 	gboolean periodic;
 	struct twitter_data *td = ic->proto_data;
-	json_value *ret;
+	JSON_Value *ret;
 	char path[64] = "", *s;
 
@@ -232,5 +237,5 @@
 	}
 
-	if ((ret = json_parse(req->reply_body, req->body_size)) == NULL) {
+	if ((ret = json_parse_string(req->reply_body)) == NULL) {
 		imcb_error(ic, "Could not retrieve %s: %s",
 		           path, "JSON parse error");
@@ -289,7 +294,7 @@
  * Fill a list of ids.
  */
-static gboolean twitter_xt_get_friends_id_list(json_value *node, struct twitter_xml_list *txl)
-{
-	json_value *c;
+static gboolean twitter_xt_get_friends_id_list(JSON_Value *node, struct twitter_xml_list *txl)
+{
+	JSON_Array *c;
 	int i;
 
@@ -297,21 +302,18 @@
 	txl->type = TXL_ID;
 
-	c = json_o_get(node, "ids");
-	if (!c || c->type != json_array) {
+	if (!(c = json_object_get_array(json_object(node), "ids"))) {
 		return FALSE;
 	}
 
-	for (i = 0; i < c->u.array.length; i++) {
-		if (c->u.array.values[i]->type != json_integer) {
-			continue;
-		}
+	for (i = 0; i < json_array_get_count(c); i++) {
+		jint id = json_array_get_integer(c, i);
 
 		txl->list = g_slist_prepend(txl->list,
-		                            g_strdup_printf("%" PRId64, c->u.array.values[i]->u.integer));
-	}
-
-	c = json_o_get(node, "next_cursor");
-	if (c && c->type == json_integer) {
-		txl->next_cursor = c->u.integer;
+		                            g_strdup_printf("%" PRIu64, id);
+	}
+
+	JSON_Value *next = json_object_get_value(json_object(node), "next_cursor");
+	if (next && json_type(next) == JSONInteger) {
+		txl->next_cursor = json_integer(next);
 	} else {
 		txl->next_cursor = -1;
@@ -329,5 +331,5 @@
 {
 	struct im_connection *ic;
-	json_value *parsed;
+	JSON_Value *parsed;
 	struct twitter_xml_list *txl;
 	struct twitter_data *td;
@@ -373,5 +375,5 @@
 {
 	struct im_connection *ic = req->data;
-	json_value *parsed;
+	JSON_Value *parsed;
 	struct twitter_xml_list *txl;
 	struct twitter_data *td;
@@ -418,5 +420,5 @@
 {
 	struct im_connection *ic = req->data;
-	json_value *parsed;
+	JSON_Value *parsed;
 	struct twitter_xml_list *txl;
 	struct twitter_data *td;
@@ -444,13 +446,11 @@
 	// Process the retweet ids
 	txl->type = TXL_ID;
-	if (parsed->type == json_array) {
+	if (json_type(parsed) == JSONArray) {
+		JSON_Array *arr = json_array(parsed);
 		unsigned int i;
-		for (i = 0; i < parsed->u.array.length; i++) {
-			json_value *c = parsed->u.array.values[i];
-			if (c->type != json_integer) {
-				continue;
-			}
+		for (i = 0; i < json_array_get_count(arr); i++) {
+			jint id = json_array_get_integer(arr, i);
 			txl->list = g_slist_prepend(txl->list,
-			                            g_strdup_printf("%" PRId64, c->u.integer));
+			                            g_strdup_printf("%" PRId64, id));
 		}
 	}
@@ -463,5 +463,5 @@
 }
 
-static gboolean twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl);
+static gboolean twitter_xt_get_users(JSON_Value *node, struct twitter_xml_list *txl);
 static void twitter_http_get_users_lookup(struct http_request *req);
 
@@ -504,5 +504,5 @@
 {
 	struct im_connection *ic = req->data;
-	json_value *parsed;
+	JSON_Value *parsed;
 	struct twitter_xml_list *txl;
 	GSList *l = NULL;
@@ -537,15 +537,15 @@
 }
 
-struct twitter_xml_user *twitter_xt_get_user(const json_value *node)
+struct twitter_xml_user *twitter_xt_get_user(const JSON_Object *node)
 {
 	struct twitter_xml_user *txu;
-	json_value *jv;
+	
+	if (!node)
+		return NULL;
 
 	txu = g_new0(struct twitter_xml_user, 1);
-	txu->name = g_strdup(json_o_str(node, "name"));
-	txu->screen_name = g_strdup(json_o_str(node, "screen_name"));
-
-	jv = json_o_get(node, "id");
-	txu->uid = jv->u.integer;
+	txu->name = g_strdup(json_object_get_string(node, "name"));
+	txu->screen_name = g_strdup(json_object_get_string(node, "screen_name"));
+	txu->uid = json_object_get_integer(node, "id");
 
 	return txu;
@@ -557,5 +557,5 @@
  *  - all <user>s from the <users> element.
  */
-static gboolean twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl)
+static gboolean twitter_xt_get_users(JSON_Value *node, struct twitter_xml_list *txl)
 {
 	struct twitter_xml_user *txu;
@@ -565,12 +565,16 @@
 	txl->type = TXL_USER;
 
-	if (!node || node->type != json_array) {
+	if (json_type(node) != JSONArray) {
 		return FALSE;
 	}
-
+	
 	// The root <users> node should hold the list of users <user>
 	// Walk over the nodes children.
-	for (i = 0; i < node->u.array.length; i++) {
-		txu = twitter_xt_get_user(node->u.array.values[i]);
+	JSON_Array *arr = json_array(node);
+	for (i = 0; i < json_array_get_count(arr); i++) {
+		JSON_Object *o = json_array_get_object(arr, i);
+		if (!o)
+			continue;
+		txu = twitter_xt_get_user(o);
 		if (txu) {
 			txl->list = g_slist_prepend(txl->list, txu);
@@ -587,5 +591,5 @@
 #endif
 
-static void expand_entities(char **text, const json_value *node, const json_value *extended_node);
+static void expand_entities(char **text, const JSON_Object *node, const JSON_Object *extended_node);
 
 /**
@@ -597,12 +601,12 @@
  *  - the user in a twitter_xml_user struct.
  */
-static struct twitter_xml_status *twitter_xt_get_status(const json_value *node)
+static struct twitter_xml_status *twitter_xt_get_status(const JSON_Object *node)
 {
 	struct twitter_xml_status *txs = {0};
-	const json_value *rt = NULL;
-	const json_value *text_value = NULL;
-	const json_value *extended_node = NULL;
-
-	if (node->type != json_object) {
+	const JSON_Object *rt = NULL;
+	const JSON_Value *text_value = NULL;
+	const JSON_Object *extended_node = NULL;
+
+	if (!node) {
 		return FALSE;
 	}
@@ -610,14 +614,14 @@
 
 	JSON_O_FOREACH(node, k, v) {
-		if (strcmp("text", k) == 0 && v->type == json_string && text_value == NULL) {
+		if (strcmp("text", k) == 0 && json_type(v) == JSONString && text_value == NULL) {
 			text_value = v;
-		} else if (strcmp("full_text", k) == 0 && v->type == json_string) {
+		} else if (strcmp("full_text", k) == 0 && json_type(v) == JSONString) {
 			text_value = v;
-		} else if (strcmp("extended_tweet", k) == 0 && v->type == json_object) {
-			text_value = json_o_get(v, "full_text");
-			extended_node = v;
-		} else if (strcmp("retweeted_status", k) == 0 && v->type == json_object) {
-			rt = v;
-		} else if (strcmp("created_at", k) == 0 && v->type == json_string) {
+		} else if (strcmp("extended_tweet", k) == 0 && json_type(v) == JSONObject) {
+			text_value = json_object_get_value(json_object(v), "full_text");
+			extended_node = json_object(v);
+		} else if (strcmp("retweeted_status", k) == 0 && (rt = json_object(v))) {
+			// Handling below.
+		} else if (strcmp("created_at", k) == 0 && json_type(v) == JSONString) {
 			struct tm parsed;
 
@@ -625,13 +629,13 @@
 			   this field. :-( Also assumes the timezone used
 			   is UTC since C time handling functions suck. */
-			if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL) {
+			if (strptime(json_string(v), TWITTER_TIME_FORMAT, &parsed) != NULL) {
 				txs->created_at = mktime_utc(&parsed);
 			}
-		} else if (strcmp("user", k) == 0 && v->type == json_object) {
-			txs->user = twitter_xt_get_user(v);
-		} else if (strcmp("id", k) == 0 && v->type == json_integer) {
-			txs->rt_id = txs->id = v->u.integer;
-		} else if (strcmp("in_reply_to_status_id", k) == 0 && v->type == json_integer) {
-			txs->reply_to = v->u.integer;
+		} else if (strcmp("user", k) == 0 && json_type(v) == JSONObject) {
+			txs->user = twitter_xt_get_user(json_object(v));
+		} else if (strcmp("id", k) == 0 && json_type(v) == JSONInteger) {
+			txs->rt_id = txs->id = json_integer(v);
+		} else if (strcmp("in_reply_to_status_id", k) == 0 && json_type(v) == JSONInteger) {
+			txs->reply_to = json_integer(v);
 		}
 	}
@@ -646,6 +650,6 @@
 			txs_free(rtxs);
 		}
-	} else if (text_value && text_value->type == json_string) {
-		txs->text = g_memdup(text_value->u.string.ptr, text_value->u.string.length + 1);
+	} else if (text_value && json_type(text_value) == JSONString) {
+		txs->text = g_strdup(json_string(text_value));
 		strip_html(txs->text);
 		expand_entities(&txs->text, node, extended_node);
@@ -663,9 +667,9 @@
  * Function to fill a twitter_xml_status struct (DM variant).
  */
-static struct twitter_xml_status *twitter_xt_get_dm(const json_value *node)
+static struct twitter_xml_status *twitter_xt_get_dm(const JSON_Object *node)
 {
 	struct twitter_xml_status *txs;
 
-	if (node->type != json_object) {
+	if (!node) {
 		return FALSE;
 	}
@@ -673,8 +677,7 @@
 
 	JSON_O_FOREACH(node, k, v) {
-		if (strcmp("text", k) == 0 && v->type == json_string) {
-			txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1);
+		if (strcmp("text", k) == 0 && (txs->text = g_strdup(json_string(v)))) {
 			strip_html(txs->text);
-		} else if (strcmp("created_at", k) == 0 && v->type == json_string) {
+		} else if (strcmp("created_at", k) == 0 && json_type(v) == JSONString) {
 			struct tm parsed;
 
@@ -682,11 +685,11 @@
 			   this field. :-( Also assumes the timezone used
 			   is UTC since C time handling functions suck. */
-			if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL) {
+			if (strptime(json_string(v), TWITTER_TIME_FORMAT, &parsed) != NULL) {
 				txs->created_at = mktime_utc(&parsed);
 			}
-		} else if (strcmp("sender", k) == 0 && v->type == json_object) {
-			txs->user = twitter_xt_get_user(v);
-		} else if (strcmp("id", k) == 0 && v->type == json_integer) {
-			txs->id = v->u.integer;
+		} else if (strcmp("sender", k) == 0 && json_type(v) == JSONObject) {
+			txs->user = twitter_xt_get_user(json_object(v));
+		} else if (strcmp("id", k) == 0 && json_type(v) == JSONInteger) {
+			txs->id = json_integer(v);
 		}
 	}
@@ -702,12 +705,12 @@
 }
 
-static void expand_entities(char **text, const json_value *node, const json_value *extended_node)
-{
-	json_value *entities, *extended_entities, *quoted;
+static void expand_entities(char **text, const JSON_Object *node, const JSON_Object *extended_node)
+{
+	JSON_Object *entities, *extended_entities, *quoted;
 	char *quote_url = NULL, *quote_text = NULL;
 
-	if (!((entities = json_o_get(node, "entities")) && entities->type == json_object))
-		return;
-	if ((quoted = json_o_get(node, "quoted_status")) && quoted->type == json_object) {
+	if (!(entities = json_object_get_object(node, "entities")))
+		return;
+	if ((quoted = json_object_get_object(node, "quoted_status"))) {
 		/* New "retweets with comments" feature. Grab the
 		 * full message and try to insert it when we run into the
@@ -722,6 +725,6 @@
 
 	if (extended_node) {
-		extended_entities = json_o_get(extended_node, "entities");
-		if (extended_entities && extended_entities->type == json_object) {
+		extended_entities = json_object_get_object(extended_node, "entities");
+		if (extended_entities) {
 			entities = extended_entities;
 		}
@@ -731,5 +734,5 @@
 		int i;
 
-		if (v->type != json_array) {
+		if (json_type(v) != JSONArray) {
 			continue;
 		}
@@ -738,14 +741,15 @@
 		}
 
-		for (i = 0; i < v->u.array.length; i++) {
+		for (i = 0; i < json_array_get_count(json_array(v)); i++) {
 			const char *format = "%s%s <%s>%s";
-
-			if (v->u.array.values[i]->type != json_object) {
+			JSON_Object *r = json_array_get_object(json_array(v), i);
+
+			if (!r) {
 				continue;
 			}
 
-			const char *kort = json_o_str(v->u.array.values[i], "url");
-			const char *disp = json_o_str(v->u.array.values[i], "display_url");
-			const char *full = json_o_str(v->u.array.values[i], "expanded_url");
+			const char *kort = json_object_get_string(r, "url");
+			const char *disp = json_object_get_string(r, "display_url");
+			const char *full = json_object_get_string(r, "expanded_url");
 			char *pos, *new;
 
@@ -779,5 +783,5 @@
  *  - the next_cursor.
  */
-static gboolean twitter_xt_get_status_list(struct im_connection *ic, const json_value *node,
+static gboolean twitter_xt_get_status_list(struct im_connection *ic, const JSON_Value *node,
                                            struct twitter_xml_list *txl)
 {
@@ -788,5 +792,5 @@
 	txl->type = TXL_STATUS;
 
-	if (node->type != json_array) {
+	if (json_type(node) != JSONArray) {
 		return FALSE;
 	}
@@ -794,6 +798,6 @@
 	// The root <statuses> node should hold the list of statuses <status>
 	// Walk over the nodes children.
-	for (i = 0; i < node->u.array.length; i++) {
-		txs = twitter_xt_get_status(node->u.array.values[i]);
+	for (i = 0; i < json_array_get_count(json_array(node)); i++) {
+		txs = twitter_xt_get_status(json_array_get_object(json_array(node), i));
 		if (!txs) {
 			continue;
@@ -1015,5 +1019,5 @@
 }
 
-static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o, gboolean from_filter);
+static gboolean twitter_stream_handle_object(struct im_connection *ic, JSON_Object *o, gboolean from_filter);
 
 static void twitter_http_stream(struct http_request *req)
@@ -1021,5 +1025,5 @@
 	struct im_connection *ic = req->data;
 	struct twitter_data *td;
-	json_value *parsed;
+	JSON_Value *parsed;
 	int len = 0;
 	char c, *nl;
@@ -1062,7 +1066,7 @@
 		req->reply_body[len] = '\0';
 
-		if ((parsed = json_parse(req->reply_body, req->body_size))) {
+		if ((parsed = json_parse_string(req->reply_body))) {
 			from_filter = (req == td->filter_stream);
-			twitter_stream_handle_object(ic, parsed, from_filter);
+			twitter_stream_handle_object(ic, json_object(parsed), from_filter);
 		}
 		json_value_free(parsed);
@@ -1078,12 +1082,12 @@
 }
 
-static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o);
+static gboolean twitter_stream_handle_event(struct im_connection *ic, JSON_Object *o);
 static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs);
 
-static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o, gboolean from_filter)
+static gboolean twitter_stream_handle_object(struct im_connection *ic, JSON_Object *o, gboolean from_filter)
 {
 	struct twitter_data *td = ic->proto_data;
 	struct twitter_xml_status *txs;
-	json_value *c;
+	JSON_Object *c;
 
 	if ((txs = twitter_xt_get_status(o))) {
@@ -1092,5 +1096,5 @@
 		txs_free(txs);
 		return ret;
-	} else if ((c = json_o_get(o, "direct_message")) &&
+	} else if ((c = json_object_get_object(o, "direct_message")) &&
 	           (txs = twitter_xt_get_dm(c))) {
 		if (g_strcasecmp(txs->user->screen_name, td->user) != 0) {
@@ -1100,12 +1104,12 @@
 		txs_free(txs);
 		return TRUE;
-	} else if ((c = json_o_get(o, "event")) && c->type == json_string) {
+	} else if (json_object_get_string(o, "event")) {
 		twitter_stream_handle_event(ic, o);
 		return TRUE;
-	} else if ((c = json_o_get(o, "disconnect")) && c->type == json_object) {
+	} else if ((c = json_object_get_object(o, "disconnect"))) {
 		/* HACK: Because we're inside an event handler, we can't just
 		   disconnect here. Instead, just change the HTTP status string
 		   into a Twitter status string. */
-		char *reason = json_o_strdup(c, "reason");
+		char *reason = g_strdup(json_object_get_string(c, "reason"));
 		if (reason) {
 			g_free(td->stream->status_string);
@@ -1146,15 +1150,14 @@
 }
 
-static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o)
+static gboolean twitter_stream_handle_event(struct im_connection *ic, JSON_Object *o)
 {
 	struct twitter_data *td = ic->proto_data;
-	json_value *source = json_o_get(o, "source");
-	json_value *target = json_o_get(o, "target");
-	const char *type = json_o_str(o, "event");
+	JSON_Object *source = json_object_get_object(o, "source");
+	JSON_Object *target = json_object_get_object(o, "target");
+	const char *type = json_object_get_string(o, "event");
 	struct twitter_xml_user *us = NULL;
 	struct twitter_xml_user *ut = NULL;
 
-	if (!type || !source || source->type != json_object
-	    || !target || target->type != json_object) {
+	if (!type || !source || !target) {
 		return FALSE;
 	}
@@ -1285,7 +1288,5 @@
 	struct twitter_filter *tf;
 	GList *users = NULL;
-	json_value *parsed;
-	json_value *id;
-	const char *name;
+	JSON_Value *parsed;
 	GString *fstr;
 	GSList *l;
@@ -1312,13 +1313,14 @@
 	}
 
-	if (parsed->type != json_array) {
+	if (json_type(parsed) != JSONArray) {
 		goto finish;
 	}
 
-	for (i = 0; i < parsed->u.array.length; i++) {
-		id = json_o_get(parsed->u.array.values[i], "id");
-		name = json_o_str(parsed->u.array.values[i], "screen_name");
-
-		if (!name || !id || id->type != json_integer) {
+	for (i = 0; i < json_array_get_count(json_array(parsed)); i++) {
+		JSON_Object *o = json_array_get_object(json_array(parsed), i);
+		jint id = json_object_get_integer(o, "id");
+		const char *name = json_object_get_string(o, "screen_name");
+
+		if (!name || !id) {
 			continue;
 		}
@@ -1328,5 +1330,5 @@
 
 			if (g_strcasecmp(tf->text, name) == 0) {
-				tf->uid = id->u.integer;
+				tf->uid = id;
 				users = g_list_delete_link(users, u);
 				break;
@@ -1573,5 +1575,5 @@
 	struct im_connection *ic = req->data;
 	struct twitter_data *td;
-	json_value *parsed;
+	JSON_Value *parsed;
 	struct twitter_xml_list *txl;
 
@@ -1613,5 +1615,5 @@
 	struct im_connection *ic = req->data;
 	struct twitter_data *td;
-	json_value *parsed;
+	JSON_Value *parsed;
 	struct twitter_xml_list *txl;
 
@@ -1654,5 +1656,6 @@
 	struct im_connection *ic = req->data;
 	struct twitter_data *td;
-	json_value *parsed, *id;
+	JSON_Value *parsed;
+	jint id;
 
 	// Check if the connection is still active.
@@ -1668,6 +1671,6 @@
 	}
 
-	if ((id = json_o_get(parsed, "id")) && id->type == json_integer) {
-		td->last_status_id = id->u.integer;
+	if ((id = json_object_get_integer(json_object(parsed), "id"))) {
+		td->last_status_id = id;
 	}
 
@@ -1797,5 +1800,6 @@
 {
 	struct im_connection *ic = req->data;
-	json_value *parsed, *id;
+	JSON_Value *parsed;
+	uint64_t id;
 	const char *name;
 
@@ -1809,14 +1813,9 @@
 	}
 
-	/* for the parson branch:
 	name = json_object_dotget_string(json_object(parsed), "user.screen_name");
 	id = json_object_get_integer(json_object(parsed), "id");
-	*/
-
-	name = json_o_str(json_o_get(parsed, "user"), "screen_name");
-	id = json_o_get(parsed, "id");
-
-	if (name && id && id->type == json_integer) {
-		twitter_log(ic, "https://twitter.com/%s/status/%" G_GUINT64_FORMAT, name, id->u.integer);
+
+	if (name && id) {
+		twitter_log(ic, "https://twitter.com/%s/status/%" G_GUINT64_FORMAT, name, id);
 	} else {
 		twitter_log(ic, "Error: could not fetch tweet url.");
Index: python/implugin.py
===================================================================
--- python/implugin.py	(revision 7a9d9684385640d7e34060469440cc80940465d8)
+++ python/implugin.py	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -0,0 +1,122 @@
+#!/usr/bin/python
+
+import bjsonrpc
+from bjsonrpc.handlers import BaseHandler
+
+import re
+import socket
+
+# List of functions an IM plugin can export. This library will indicate to
+# BitlBee which functions are actually implemented so omitted features
+# will be disabled, but note that some/many functions are simply mandatory.
+# (Currently login/-out, buddy_msg.)
+SUPPORTED_FUNCTIONS = [
+	'login', 'keepalive', 'logout', 'buddy_msg', 'set_away',
+	'send_typing', 'add_buddy', 'remove_buddy', 'add_permit',
+	'add_deny', 'rem_permit', 'rem_deny', 'get_info', 'chat_invite',
+	'chat_kick', 'chat_leave', 'chat_msg', 'chat_with', 'chat_join',
+	'chat_topic'
+]
+
+def make_version_tuple(hex):
+	"""Convert the BitlBee binary-encoded version number into something
+	more "Pythonic". Could use distutils.version instead but its main
+	benefit appears to be string parsing which here is not that useful."""
+
+	return (hex >> 16, (hex >> 8) & 0xff, hex & 0xff)
+
+class RpcForwarder(object):
+	"""Tiny object that forwards RPCs from local Python code to BitlBee
+	with a marginally nicer syntax. This layer could eventually be
+	used to add basic parameter checking though I don't think that should
+	be done here."""
+	
+	def __init__(self, methods, target):
+		for m in methods:
+			# imc(b)_ prefix is not useful here, chop it.
+			# (Maybe do this in BitlBee already as well.)
+			newname = re.sub("^imcb?_", "", m)
+			self.__setattr__(newname, target.__getattr__(m))
+
+class BitlBeeIMPlugin(BaseHandler):
+	# Protocol name to be used in the BitlBee CLI, etc.
+	NAME = "rpc-test"
+
+	# See account.h (TODO: Add constants.)
+	ACCOUNT_FLAGS = 0
+	
+	# Supported away states. If your protocol supports a specific set of
+	# away states, put them in a list in this variable.
+	AWAY_STATES = None
+
+	SETTINGS = {
+		"oauth": {
+			"default": False,
+			"type": "bool",
+		},
+		"test": {
+			"default": 123,
+			"type": "int",
+		},
+		"stringetje": {
+			"default": "testje",
+			"flags": 0x04,
+		}
+	}
+	_settings_values = {}
+	
+	# Filled in during initialisation:
+	# Version number as a three-tuple, so 3.2 becomes (3, 2, 0).
+	bitlbee_version = None
+	# Full version string
+	bitlbee_version_str = None
+	# Will become an RpcForwarder object to call into BitlBee
+	bee = None
+	
+	@classmethod
+	def _factory(cls, *args, **kwargs):
+		def handler_factory(connection):
+			handler = cls(connection, *args, **kwargs)
+			return handler
+		return handler_factory
+	
+	def init(self, bee):
+		self.bee = RpcForwarder(bee["method_list"], self._conn.call)
+		self.bitlbee_version = make_version_tuple(bee["version"])
+		self.bitlbee_version_str = bee["version_str"]
+
+		return {
+			"name": self.NAME,
+			"method_list": list(set(dir(self)) & set(SUPPORTED_FUNCTIONS)),
+			"account_flags": self.ACCOUNT_FLAGS,
+			"away_state_list": self.AWAY_STATES,
+			"settings": self.SETTINGS,
+		}
+
+	def login(self, account):
+		for key, value in account.get("settings", {}).iteritems():
+			self.set_set(key, value)
+
+	def set_set(self, key, value):
+		self._settings_values[key] = value
+		try:
+			func = self.__getattribute__("set_set_%s" % key)
+		except AttributeError:
+			return
+		func(key, value)
+	
+	def setting(self, key):
+		"""Throws KeyError if the setting does not exist!"""
+		return self._settings_values[key]
+
+
+def RunPlugin(plugin, debug=False):
+	sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+	sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+	sock.bind("/tmp/rpcplugins/%s.sock" % plugin.NAME)
+	sock.listen(3)
+	
+	srv = bjsonrpc.server.Server(sock, plugin._factory())
+	
+	srv.debug_socket(debug)
+	srv.serve()
Index: python/newsblur.py
===================================================================
--- python/newsblur.py	(revision 7a9d9684385640d7e34060469440cc80940465d8)
+++ python/newsblur.py	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -0,0 +1,95 @@
+#!/usr/bin/python
+
+import operator
+import re
+
+import requests
+
+import implugin
+
+class NewsBlurPlugin(implugin.BitlBeeIMPlugin):
+	NAME = "newsblur"
+	ACCOUNT_FLAGS = 0
+	SETTINGS = {
+		"backlog": {
+			"default": 20,
+			"type": "int",
+		},
+	}
+	
+	BASE_URL = "https://newsblur.com"
+	
+	def url(self, path):
+		return (self.BASE_URL + path)
+
+	def login(self, account):
+		super(NewsBlurPlugin, self).login(account)
+		self.ua = requests.Session()
+		creds = {"username": account["user"], "password": account["pass"]}
+		r = self.ua.post(self.url("/api/login"), creds)
+		self.bee.log("You're running BitlBee %d.%d.%d" % self.bitlbee_version)
+		if r.status_code != 200:
+			self.bee.error("HTTP error %d" % r.status_code)
+			self.bee.logout(True)
+		elif r.json()["errors"]:
+			self.bee.error("Authentication error")
+			self.bee.logout(False)
+		else:
+			self.bee.add_buddy("rss", None)
+			self.bee.connected()
+			self.seen_hashes = set()
+			self.keepalive()
+
+	def logout(self):
+		self.bee.log("Ok bye!")
+
+	def buddy_msg(self, handle, msg, flags):
+		feed = self.feeds[handle]
+		cmd = re.split(r"\s+", msg)
+	
+	def set_set_backlog(self, setting, value):
+		print "Setting %s changed to %r" % (setting, value)
+	
+	# BitlBee will call us here every minute which is actually a neat way
+	# to get periodic work (like RSS polling) scheduled. :-D
+	def keepalive(self):
+		r = self.ua.post(
+			self.url("/reader/unread_story_hashes"),
+			{"include_timestamps": True})
+		if r.status_code != 200:
+			self.bee.error("HTTP error %d" % r.status_code)
+			return
+
+		# Throw all unread-post hashes in a flat list and sort it by posting time.
+		feed_hashes = r.json()["unread_feed_story_hashes"]
+		all_hashes = []
+		for feed, hashes in feed_hashes.iteritems():
+			all_hashes += [tuple(h) for h in hashes]
+		all_hashes.sort(key=operator.itemgetter(1))
+		
+		# Look at the most recent posts, grab the ones we haven't shown yet.
+		req_hashes = []
+		for hash, _ in all_hashes[-self.setting("backlog"):]:
+			if hash not in self.seen_hashes:
+				req_hashes.append(hash)
+		
+		if not req_hashes:
+			return
+		
+		# Grab post details.
+		r = self.ua.post(self.url("/reader/river_stories"), {"h": req_hashes})
+		if r.status_code != 200:
+			self.bee.error("HTTP error %d" % r.status_code)
+			return
+		
+		# Response is not in the order we requested. :-( Make it a hash
+		# and reconstruct order from our request.
+		stories = {s["story_hash"]: s for s in r.json()["stories"]}
+		for s in (stories[hash] for hash in req_hashes):
+			line = "%(story_title)s <%(story_permalink)s>" % s
+			ts = int(s.get("story_timestamp", "0"))
+			self.bee.buddy_msg("rss", line, 0, ts)
+			self.seen_hashes.add(s["story_hash"])
+
+
+implugin.RunPlugin(NewsBlurPlugin, debug=True)
Index: python/wa.py
===================================================================
--- python/wa.py	(revision 7a9d9684385640d7e34060469440cc80940465d8)
+++ python/wa.py	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -0,0 +1,542 @@
+#!/usr/bin/python
+
+import collections
+import logging
+import threading
+import time
+
+import yowsup
+
+from yowsup.layers.auth                        import YowAuthenticationProtocolLayer
+from yowsup.layers.protocol_acks               import YowAckProtocolLayer
+from yowsup.layers.protocol_chatstate          import YowChatstateProtocolLayer
+from yowsup.layers.protocol_contacts           import YowContactsIqProtocolLayer
+from yowsup.layers.protocol_groups             import YowGroupsProtocolLayer
+from yowsup.layers.protocol_ib                 import YowIbProtocolLayer
+from yowsup.layers.protocol_iq                 import YowIqProtocolLayer
+from yowsup.layers.protocol_messages           import YowMessagesProtocolLayer
+from yowsup.layers.protocol_notifications      import YowNotificationsProtocolLayer
+from yowsup.layers.protocol_presence           import YowPresenceProtocolLayer
+from yowsup.layers.protocol_privacy            import YowPrivacyProtocolLayer
+from yowsup.layers.protocol_profiles           import YowProfilesProtocolLayer
+from yowsup.layers.protocol_receipts           import YowReceiptProtocolLayer
+from yowsup.layers.network                     import YowNetworkLayer
+from yowsup.layers.coder                       import YowCoderLayer
+from yowsup.stacks import YowStack, YowStackBuilder
+from yowsup.common import YowConstants
+from yowsup.layers import YowLayerEvent
+from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS
+from yowsup import env
+
+from yowsup.layers.interface                             import YowInterfaceLayer, ProtocolEntityCallback
+from yowsup.layers.protocol_acks.protocolentities        import *
+from yowsup.layers.protocol_chatstate.protocolentities   import *
+from yowsup.layers.protocol_contacts.protocolentities    import *
+from yowsup.layers.protocol_groups.protocolentities      import *
+from yowsup.layers.protocol_ib.protocolentities          import *
+from yowsup.layers.protocol_iq.protocolentities          import *
+from yowsup.layers.protocol_media.mediauploader import MediaUploader
+from yowsup.layers.protocol_media.protocolentities       import *
+from yowsup.layers.protocol_messages.protocolentities    import *
+from yowsup.layers.protocol_notifications.protocolentities import *
+from yowsup.layers.protocol_presence.protocolentities    import *
+from yowsup.layers.protocol_privacy.protocolentities     import *
+from yowsup.layers.protocol_profiles.protocolentities    import *
+from yowsup.layers.protocol_receipts.protocolentities    import *
+from yowsup.layers.axolotl.protocolentities.iq_key_get import GetKeysIqProtocolEntity
+
+import implugin
+
+logger = logging.getLogger("yowsup.layers.logger.layer")
+logger.setLevel(logging.DEBUG)
+ch = logging.StreamHandler()
+ch.setLevel(logging.DEBUG)
+logger.addHandler(ch)
+
+"""
+TODO/Things I'm unhappy about:
+
+About the fact that WhatsApp is a rubbish protocol that happily rejects
+every second stanza you send it if you're trying to implement a client that
+doesn't keep local state. See how to cope with that.. It'd help if Yowsup
+came with docs on what a normal login sequence looks like instead of just
+throwing some stanzas over a wall but hey.
+
+The randomness of where which bits/state live, in the implugin and the
+yowsup layer. Can't really merge this but at least state should live in
+one place.
+
+Mix of silly CamelCase and proper_style. \o/
+
+Most important: This is NOT thread-clean. implugin can call into yowsup
+cleanly by throwing closures into a queue, but there's no mechanism in
+the opposite direction, I'll need to cook up some hack to make this
+possible through bjsonrpc's tiny event loop. I think I know how...
+
+And more. But let's first get this into a state where it even works..
+"""
+
+class BitlBeeLayer(YowInterfaceLayer):
+
+	def __init__(self, *a, **kwa):
+		super(BitlBeeLayer, self).__init__(*a, **kwa)
+		# Offline messages are sent while we're still logging in.
+		self.msg_queue = []
+
+	def receive(self, entity):
+		print "Received: %r" % entity
+		#print entity
+		super(BitlBeeLayer, self).receive(entity)
+
+	def Ship(self, entity):
+		"""Send an entity into Yowsup, but through the correct thread."""
+		print "Queueing: %s" % entity.getTag()
+		#print entity
+		def doit():
+			self.toLower(entity)
+		self.getStack().execDetached(doit)
+
+	@ProtocolEntityCallback("success")
+	def onSuccess(self, entity):
+		self.b = self.getStack().getProp("org.bitlbee.Bijtje")
+		self.cb = self.b.bee
+		self.b.yow = self
+		
+		self.cb.log("Authenticated, syncing contact list")
+		
+		# We're done once this set is empty.
+		self.todo = set(["contacts", "groups", "ping"])
+		
+		# Supposedly WA can also do national-style phone numbers without
+		# a + prefix BTW (relative to I guess the user's country?). I
+		# don't want to support this at least for now.
+		numbers = [("+" + x.split("@")[0]) for x in self.cb.get_local_contacts()]
+		self.toLower(GetSyncIqProtocolEntity(numbers))
+		self.toLower(ListGroupsIqProtocolEntity())
+		self.b.keepalive()
+		
+		try:
+			self.toLower(PresenceProtocolEntity(name=self.b.setting("name")))
+		except KeyError:
+			pass
+
+	def check_connected(self, done):
+		if not self.todo:
+			return
+		self.todo.remove(done)
+		if not self.todo:
+			self.cb.connected()
+			self.flush_msg_queue()
+	
+	def flush_msg_queue(self):
+		for msg in self.msg_queue:
+			self.onMessage(msg)
+		self.msg_queue = None
+	
+	@ProtocolEntityCallback("failure")
+	def onFailure(self, entity):
+		self.b = self.getStack().getProp("org.bitlbee.Bijtje")
+		self.cb = self.b.bee
+		self.cb.error(entity.getReason())
+		self.cb.logout(False)
+
+	def onEvent(self, event):
+		# TODO: Make this work without, hmm, over-recursing. (This handler
+		# getting called when we initiated the disconnect, which upsets yowsup.)
+		if event.getName() == "orgopenwhatsapp.yowsup.event.network.disconnected":
+			self.cb.error(event.getArg("reason"))
+			self.cb.logout(True)
+			self.getStack().execDetached(self.daemon.StopDaemon)
+		else:
+			print "Received event: %s name %s" % (event, event.getName())
+	
+	@ProtocolEntityCallback("presence")
+	def onPresence(self, pres):
+		if pres.getFrom() == self.b.account["user"]:
+			# WA returns our own presence. Meh.
+			return
+		
+		# Online/offline is not really how WA works. Let's show everyone
+		# as online but unavailable folks as away. This also solves the
+		# problem of offline->IRC /quit causing the persons to leave chat
+		# channels as well (and not reappearing there when they return).
+		status = 8 | 1  # MOBILE | ONLINE
+		if pres.getType() == "unavailable":
+			status |= 4  # AWAY
+		self.cb.buddy_status(pres.getFrom(), status, None, None)
+		
+		try:
+			# Last online time becomes idle time which I guess is
+			# sane enough?
+			self.cb.buddy_times(pres.getFrom(), 0, int(pres.getLast()))
+		except (ValueError, TypeError):
+			# Could be "error" or, more likely, "deny", or None.
+			pass
+	
+	@ProtocolEntityCallback("message")
+	def onMessage(self, msg):
+		if self.todo:
+			# We're still logging in, so wait.
+			self.msg_queue.append(msg)
+			return
+
+		self.b.show_message(msg)
+
+		# ACK is required! So only use return above in case of errors.
+		# (So that we will/might get a retry after restarting.)
+		self.toLower(OutgoingReceiptProtocolEntity(msg.getId(), msg.getFrom()))
+
+	@ProtocolEntityCallback("receipt")
+	def onReceipt(self, entity):
+		ack = OutgoingAckProtocolEntity(entity.getId(), entity.getTag(),
+		                                entity.getType(), entity.getFrom())
+		self.toLower(ack)
+
+	@ProtocolEntityCallback("iq")
+	def onIq(self, entity):
+		if isinstance(entity, ResultSyncIqProtocolEntity):
+			return self.onSyncResult(entity)
+		elif isinstance(entity, ListGroupsResultIqProtocolEntity):
+			return self.onListGroupsResult(entity)
+		elif type(entity) == IqProtocolEntity:  # Pong has no type, sigh.
+			self.b.last_pong = time.time()
+			if self.todo:
+				return self.onLoginPong()
+	
+	def onSyncResult(self, entity):
+		# TODO HERE AND ELSEWHERE: Thread idiocy happens when going
+		# from here to the IMPlugin. Check how bjsonrpc lets me solve that.
+		for num, jid in entity.inNumbers.iteritems():
+			self.toLower(SubscribePresenceProtocolEntity(jid))
+			self.cb.add_buddy(jid, "")
+		if entity.outNumbers:
+			self.cb.error("Not on WhatsApp: %s" %
+			              ", ".join(entity.outNumbers.keys()))
+		if entity.invalidNumbers:
+			self.cb.error("Invalid numbers: %s" %
+			              ", ".join(entity.invalidNumbers))
+
+		#self.getStatuses(entity.inNumbers.values())
+		self.check_connected("contacts")
+
+	def onSyncResultFail(self):
+		# Whatsapp rate-limits sync stanzas, so in case of failure
+		# just assume all contacts are valid.
+		for jid in self.cb.get_local_contacts():
+			self.toLower(SubscribePresenceProtocolEntity(jid))
+			self.cb.add_buddy(jid, "")
+		#self.getStatuses?
+		self.check_connected("contacts")
+
+	def onListGroupsResult(self, groups):
+		"""Save group info for later if the user decides to join."""
+		for g in groups.getGroups():
+			jid = g.getId()
+			if "@" not in jid:
+				jid += "@g.us"
+			group = self.b.groups[jid]
+			try:
+				group["participants"] = g.getParticipants().keys()
+			except AttributeError:
+				# Depends on a change I made to yowsup that may
+				# or may not get merged..
+				group["participants"] = []
+			
+			# Save it. We're going to mix ListGroups elements and
+			# Group-Subject notifications there, which don't have
+			# consistent fieldnames for the same bits of info \o/
+			g.getSubjectTimestamp = g.getSubjectTime
+			group["topic"] = g
+
+		self.check_connected("groups")
+
+	def onLoginPong(self):
+		if "contacts" in self.todo:
+			# Shitty Whatsapp rejected the sync request, and
+			# annoying Yowsup doesn't inform on error responses.
+			# So instead, if we received no response to it but
+			# did get our ping back, declare failure.
+			self.onSyncResultFail()
+		if "groups" in self.todo:
+			# Well fuck this. Just reject ALL the things!
+			# Maybe I don't need this one then.
+			self.check_connected("groups")
+		self.check_connected("ping")
+
+	def getStatuses(self, contacts):
+		return # Disabled since yowsup won't give us the result...
+		self.toLower(GetStatusIqProtocolEntity(contacts))
+		self.todo.add("statuses")
+
+	@ProtocolEntityCallback("notification")
+	def onNotification(self, ent):
+		if isinstance(ent, StatusNotificationProtocolEntity):
+			return self.onStatusNotification(ent)
+		elif isinstance(ent, SubjectGroupsNotificationProtocolEntity):
+			return self.onGroupSubjectNotification(ent)
+
+	def onStatusNotification(self, status):
+		print "New status for %s: %s" % (status.getFrom(), status.status)
+		self.cb.buddy_status_msg(status.getFrom(), status.status)
+	
+	def onGroupSubjectNotification(self, sub):
+		print "New /topic for %s: %s" % (sub.getFrom(), sub.getSubject())
+		group = self.b.groups[sub.getFrom()]
+		group["topic"] = sub
+		id = group.get("id", None)
+		if id is not None:
+			self.cb.chat_topic(id, sub.getSubjectOwner(),
+			                   sub.getSubject(), sub.getSubjectTimestamp())
+
+	@ProtocolEntityCallback("media")
+	def onMedia(self, med):
+		"""Your PC better be MPC3 compliant!"""
+		print "YAY MEDIA! %r" % med
+		print med
+
+	#@ProtocolEntityCallback("chatstate")
+	#def onChatstate(self, entity):
+	#	print(entity)
+
+
+class YowsupDaemon(threading.Thread):
+	daemon = True
+	stack = None
+
+	class Terminate(Exception):
+		pass
+
+	def run(self):
+		try:
+			self.stack.loop(timeout=0.2, discrete=0.2, count=1)
+		except YowsupDaemon.Terminate:
+			print "Exiting loop!"
+			pass
+	
+	def StopDaemon(self):
+		# Ugly, but yowsup offers no "run single iteration" version
+		# of their event loop :-(
+		raise YowsupDaemon.Terminate
+
+
+class YowsupIMPlugin(implugin.BitlBeeIMPlugin):
+	NAME = "wa"
+	SETTINGS = {
+		"cc": {
+			# Country code. Seems to be required for registration only.
+			"type": "int",
+		},
+		"reg_mode": {
+			"default": "sms",
+		},
+		"name": {
+			"flags": 0x100, # NULL_OK
+		},
+		# EW! Need to include this setting to trick BitlBee into
+		# doing registration instead of refusing to login w/o pwd.
+		# TODO: Make this a flag instead of faking oauth.
+		"oauth": {
+			"default": True,
+		},
+	}
+	AWAY_STATES = ["Away"]
+	ACCOUNT_FLAGS = 14 # HANDLE_DOMAINS + STATUS_MESSAGE + LOCAL_CONTACTS
+	# TODO: HANDLE_DOMAIN in right place (add ... ... nick bug)
+	PING_INTERVAL = 299 # seconds
+	PING_TIMEOUT = 360 # seconds
+
+	def login(self, account):
+		super(YowsupIMPlugin, self).login(account)
+		self.account = account
+		self.number = self.account["user"].split("@")[0]
+		self.registering = False
+		if not self.account["pass"]:
+			return self._register()
+		
+		self.stack = self._build_stack()
+		self.daemon = YowsupDaemon(name="yowsup")
+		self.daemon.stack = self.stack
+		self.daemon.start()
+		self.bee.log("Started yowsup thread")
+		
+		self.groups = collections.defaultdict(dict)
+		self.groups_by_id = {}
+
+		self.next_ping = None
+		self.last_pong = time.time()
+
+	def keepalive(self):
+		if (time.time() - self.last_pong) > self.PING_TIMEOUT:
+			self.bee.error("Ping timeout")
+			self.bee.logout(True)
+			return
+		if self.next_ping and (time.time() < self.next_ping):
+			return
+		self.yow.Ship(PingIqProtocolEntity(to="s.whatsapp.net"))
+		self.next_ping = time.time() + self.PING_INTERVAL
+
+	def logout(self):
+		self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
+		self.stack.execDetached(self.daemon.StopDaemon)
+
+	def _register(self):
+		self.registering = True
+		self.bee.log("New account, starting registration")
+		from yowsup.registration import WACodeRequest
+		cr = WACodeRequest(str(self.setting("cc")), self.number,
+		                   "000", "000", "000", "000",
+		                   self.setting("reg_mode"))
+		res = cr.send()
+		res = {k: v for k, v in res.iteritems() if v is not None}
+		if res.get("status", "") != "sent":
+			self.bee.error("Failed to start registration: %r" % res)
+			self.bee.logout(False)
+			return
+		
+		text = ("Registration request sent. You will receive a SMS or "
+		        "call with a confirmation code. Please respond to this "
+		        "message with that code.")
+		sender = "wa_%s" % self.number
+		self.bee.add_buddy(sender, "")
+		self.bee.buddy_msg(sender, text, 0, 0)
+
+	def _register_confirm(self, code):
+		from yowsup.registration import WARegRequest
+		code = code.strip().replace("-", "")
+		rr = WARegRequest(str(self.setting("cc")), self.number, code)
+		res = rr.send()
+		res = {k: v for k, v in res.iteritems() if v is not None}
+		if (res.get("status", "") != "ok") or (not self.get("pw", "")):
+			self.bee.error("Failed to finish registration: %r" % res)
+			self.bee.logout(False)
+			return
+		self.bee.log("Registration finished, attempting login")
+		self.bee.set_setstr("password", res["pw"])
+		self.account["pass"] = res["pw"]
+		self.login(self.account)
+
+	def buddy_msg(self, to, text, flags):
+		if self.registering:
+			return self._register_confirm(text)
+		msg = TextMessageProtocolEntity(text, to=to)
+		self.yow.Ship(msg)
+
+	def add_buddy(self, handle, _group):
+		self.yow.Ship(GetSyncIqProtocolEntity(
+		    ["+" + handle.split("@")[0]], mode=GetSyncIqProtocolEntity.MODE_DELTA))
+
+	def remove_buddy(self, handle, _group):
+		self.yow.Ship(UnsubscribePresenceProtocolEntity(handle))
+
+	def set_away(self, state, status):
+		print "Trying to set status to %r, %r" % (state, status)
+		if state:
+			# Only one option offered so None = available, not None = away.
+			self.yow.Ship(AvailablePresenceProtocolEntity())
+		else:
+			self.yow.Ship(UnavailablePresenceProtocolEntity())
+		if status:
+			self.yow.Ship(SetStatusIqProtocolEntity(status))
+
+	def set_set_name(self, _key, value):
+		#self.yow.Ship(PresenceProtocolEntity(name=value))
+		pass
+
+	def chat_join(self, id, name, _nick, _password, settings):
+		print "New chat created with id: %d" % id
+		group = self.groups[name]
+		group.update({"id": id, "name": name})
+		self.groups_by_id[id] = group
+		
+		gi = group.get("topic", None)
+		if gi:
+			self.bee.chat_topic(id, gi.getSubjectOwner(),
+			                    gi.getSubject(), gi.getSubjectTimestamp())
+		
+		# WA doesn't really have a concept of joined or not, just
+		# long-term membership. Let's just sync state (we have
+		# basic info but not yet a member list) and ACK the join
+		# once that's done.
+		# Well except that WA/YS killed this one. \o/
+		#self.yow.Ship(ParticipantsGroupsIqProtocolEntity(name))
+		
+		# So for now do without a participant list..
+		self.chat_join_participants(group)
+		self.chat_send_backlog(group)
+
+	def chat_join_participants(self, group):
+		for p in group.get("participants", []):
+			if p != self.account["user"]:
+				self.bee.chat_add_buddy(group["id"], p)
+
+	def chat_send_backlog(self, group):
+		# Add the user themselves last to avoid a visible join flood.
+		self.bee.chat_add_buddy(group["id"], self.account["user"])
+		for msg in group.setdefault("queue", []):
+			self.show_message(msg)
+		del group["queue"]
+	
+	def chat_msg(self, id, text, flags):
+		msg = TextMessageProtocolEntity(text, to=self.groups_by_id[id]["name"])
+		self.yow.Ship(msg)
+
+	def chat_leave(self, id):
+		# WA never really let us leave, so just disconnect id and jid.
+		group = self.groups_by_id[id]
+		del self.groups_by_id[id]
+		del group["id"]
+
+	def _build_stack(self):
+		creds = (self.number, self.account["pass"])
+
+		stack = (YowStackBuilder()
+		         .pushDefaultLayers(True)
+		         .push(BitlBeeLayer)
+		         .build())
+		stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, creds)
+		stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0])
+		stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN)
+		stack.setProp(YowCoderLayer.PROP_RESOURCE, env.YowsupEnv.getCurrent().getResource())
+		try:
+			stack.setProp(YowIqProtocolLayer.PROP_PING_INTERVAL, 0)
+		except AttributeError:
+			# Ping setting only exists since May 2015.
+			from yowsup.layers.protocol_iq.layer import YowPingThread
+			YowPingThread.start = lambda x: None
+
+		stack.setProp("org.bitlbee.Bijtje", self)
+
+		stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
+
+		return stack
+
+
+	# Not RPCs from here on.
+	def show_message(self, msg):
+		if hasattr(msg, "getBody"):
+			text = msg.getBody()
+		elif hasattr(msg, "getCaption") and hasattr(msg, "getMediaUrl"):
+			lines = []
+			if msg.getMediaUrl():
+				lines.append(msg.getMediaUrl())
+			else:
+				lines.append("<Broken link>")
+			if msg.getCaption():
+				lines.append(msg.getCaption())
+			text = "\n".join(lines)
+		else:
+			text = "Message of unknown type %r" % type(msg)
+
+		if msg.getParticipant():
+			group = self.groups[msg.getFrom()]
+			if "id" in group:
+				self.bee.chat_add_buddy(group["id"], msg.getParticipant())
+				self.bee.chat_msg(group["id"], msg.getParticipant(), text, 0, msg.getTimestamp())
+			else:
+				self.bee.log("Warning: Activity in room %s" % msg.getFrom())
+				self.groups[msg.getFrom()].setdefault("queue", []).append(msg)
+		else:
+			self.bee.buddy_msg(msg.getFrom(), text, 0, msg.getTimestamp())
+
+
+implugin.RunPlugin(YowsupIMPlugin, debug=True)
Index: root_commands.c
===================================================================
--- root_commands.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ root_commands.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -509,5 +509,4 @@
 				con = "";
 			}
-
 			if (a->prpl == &protocol_missing) {
 				protocol = g_strdup_printf("%s (missing!)", set_getstr(&a->set, "_protocol_name"));
@@ -701,4 +700,20 @@
 		irc_rootmsg(irc, "That account is not on-line");
 		return;
+	} else if (add_on_server && !a->prpl->add_buddy) {
+		irc_rootmsg(irc, "IM protocol does not support contact list modification");
+		return;
+	}
+
+	if ((a->flags & ACC_FLAG_HANDLE_DOMAINS) && cmd[2][0] != '_' &&
+	    (!(s = strchr(cmd[2], '@')) || s[1] == '\0')) {
+		/* If there's no @ or it's the last char, append the user's
+		   domain name now. Exclude handles starting with a _ so
+		   adding _xmlconsole will keep working. */
+		if (s) {
+			*s = '\0';
+		}
+		if ((s = strchr(a->user, '@'))) {
+			cmd[2] = handle = g_strconcat(cmd[2], s, NULL);
+		}
 	}
 
@@ -715,17 +730,4 @@
 	}
 
-	if ((a->flags & ACC_FLAG_HANDLE_DOMAINS) && cmd[2][0] != '_' &&
-	    (!(s = strchr(cmd[2], '@')) || s[1] == '\0')) {
-		/* If there's no @ or it's the last char, append the user's
-		   domain name now. Exclude handles starting with a _ so
-		   adding _xmlconsole will keep working. */
-		if (s) {
-			*s = '\0';
-		}
-		if ((s = strchr(a->user, '@'))) {
-			cmd[2] = handle = g_strconcat(cmd[2], s, NULL);
-		}
-	}
-
 	if (add_on_server) {
 		irc_channel_t *ic;
@@ -771,5 +773,11 @@
 	s = g_strdup(bu->handle);
 
-	bu->ic->acc->prpl->remove_buddy(bu->ic, bu->handle, NULL);
+	if (bu->ic->acc->prpl->remove_buddy) {
+		bu->ic->acc->prpl->remove_buddy(bu->ic, bu->handle, NULL);
+	} else {
+		irc_rootmsg(irc, "IM protocol does not support contact list modification, "
+		                 "removal will likely not be permanent");
+	}
+
 	nick_del(bu);
 	if (g_slist_find(irc->users, iu)) {
Index: storage_xml.c
===================================================================
--- storage_xml.c	(revision 4a9c6b0b15eb3738897dc1635fda2e4be67414ad)
+++ storage_xml.c	(revision 7a9d9684385640d7e34060469440cc80940465d8)
@@ -114,5 +114,5 @@
 	char *pass_b64 = NULL;
 	unsigned char *pass_cr = NULL;
-	int pass_len, local = 0;
+	int pass_len;
 	struct prpl *prpl = NULL;
 	account_t *acc;
@@ -133,5 +133,4 @@
 			prpl = (struct prpl*) &protocol_missing;
 		}
-		local = protocol_account_islocal(protocol);
 	}
 
@@ -161,7 +160,4 @@
 	if (tag) {
 		set_setstr(&acc->set, "tag", tag);
-	}
-	if (local) {
-		acc->flags |= ACC_FLAG_LOCAL;
 	}
 	if (locked && !g_strcasecmp(locked, "true")) {
