--- cel/cel_pgsql.c.orig2
+++ cel/cel_pgsql.c
@@ -58,9 +58,10 @@
 
 #define DATE_FORMAT "%Y-%m-%d %T.%6q"
 
-#define PGSQL_BACKEND_NAME "CEL PGSQL backend"
+#define PGSQL_MIN_VERSION_SCHEMA 70300
 
-static char *config = "cel_pgsql.conf";
+static const char name[] = "CEL PostgreSQL backend";
+static const char config[] = "cel_pgsql.conf";
 
 static char *pghostname;
 static char *pgdbname;
@@ -69,20 +70,22 @@
 static char *pgappname;
 static char *pgdbport;
 static char *table;
+static char *encoding;
+static char *tz;
 
 static int connected = 0;
-static int maxsize = 512, maxsize2 = 512;
+/* Optimization to reduce number of memory allocations */
+static int maxsize1 = 512, maxsize2 = 512;
 
 /*! \brief show_user_def is off by default */
-#define CEL_SHOW_USERDEF_DEFAULT	0
+#define CEL_SHOW_USERDEF_DEFAULT 0
 
 /*! TRUE if we should set the eventtype field to USER_DEFINED on user events. */
 static unsigned char cel_show_user_def;
 
 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
 
-static PGconn	*conn = NULL;
-static PGresult	*result = NULL;
+static PGconn *conn = NULL;
 
 struct columns {
 	char *name;
@@ -90,50 +93,42 @@
 	int len;
 	unsigned int notnull:1;
 	unsigned int hasdefault:1;
-	AST_RWLIST_ENTRY(columns) list;
+	AST_LIST_ENTRY(columns) entry;
 };
 
-static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
+static AST_LIST_HEAD_STATIC(psql_columns, columns);
 
-#define LENGTHEN_BUF1(size) \
-	do { \
-		/* Lengthen buffer, if necessary */ \
-		if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
-			if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) { \
-				ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CEL '%s:%s' failed.\n", pghostname, table); \
-				ast_free(sql); \
-				ast_free(sql2); \
-				AST_RWLIST_UNLOCK(&psql_columns); \
-				return; \
-			} \
-		} \
-	} while (0)
+static void empty_columns(void)
+{
+	struct columns *current;
 
-#define LENGTHEN_BUF2(size) \
-	do { \
-		if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) { \
-			if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) { \
-				ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CEL '%s:%s' failed.\n", pghostname, table); \
-				ast_free(sql); \
-				ast_free(sql2); \
-				AST_RWLIST_UNLOCK(&psql_columns); \
-				return; \
-			} \
-		} \
-	} while (0)
+	while ((current = AST_LIST_REMOVE_HEAD(&psql_columns, entry))) {
+		ast_free(current);
+	}
+}
 
-static void pgsql_reconnect(void)
+static void pgsql_disconnect(void)
+{
+	if (conn) {
+		PQfinish(conn);
+		conn = NULL;
+	}
+
+	connected = 0;
+}
+
+static void pgsql_connect(void)
 {
 	struct ast_str *conn_info = ast_str_create(128);
-	if (!conn_info) {
+	struct columns *cur;
+	char *pgerror;
+
+	if (conn_info == NULL) {
 		ast_log(LOG_ERROR, "Failed to allocate memory for connection string.\n");
 		return;
 	}
 
-	if (conn) {
-		PQfinish(conn);
-		conn = NULL;
-	}
+	pgsql_disconnect();
 
 	ast_str_set(&conn_info, 0, "host=%s port=%s dbname=%s user=%s",
 		pghostname, pgdbport, pgdbname, pgdbuser);
@@ -147,15 +142,136 @@
 	}
 
 	conn = PQconnectdb(ast_str_buffer(conn_info));
+
 	ast_free(conn_info);
+
+	if (PQstatus(conn) == CONNECTION_OK) {
+		char sql[768];
+		char *fname, *ftype, *flen, *fnotnull, *fdef;
+		PGresult *result;
+		int i, rows, version;
+
+		ast_debug(1, "Successfully connected to PostgreSQL database.\n");
+		connected = 1;
+
+		if (PQsetClientEncoding(conn, encoding)) {
+#ifdef HAVE_PGSQL_pg_encoding_to_char
+			ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
+#else
+			ast_log(LOG_WARNING, "Failed to set encoding to '%s'. Encoding set to default.\n", encoding);
+#endif
+		}
+
+		version = PQserverVersion(conn);
+
+		if (version >= PGSQL_MIN_VERSION_SCHEMA) {
+			char *schemaname, *tablename, *tmp_schemaname, *tmp_tablename;
+			size_t len;
+			if (strchr(table, '.')) {
+				tmp_schemaname = ast_strdupa(table);
+				tmp_tablename = strrchr(tmp_schemaname, '.');
+				*tmp_tablename++ = '\0';
+			} else {
+				tmp_schemaname = "";
+				tmp_tablename = table;
+			}
+			len = strlen(tmp_tablename);
+			tablename = ast_alloca(len * 2 + 1);
+			PQescapeStringConn(conn, tablename, tmp_tablename, len, NULL);
+
+			len = strlen(tmp_schemaname);
+			schemaname = ast_alloca(len * 2 + 1);
+			PQescapeStringConn(conn, schemaname, tmp_schemaname, len, NULL);
+
+			snprintf(sql, sizeof(sql), "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM (((pg_catalog.pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND c.relname = '%s' AND n.nspname = %s%s%s) INNER JOIN pg_catalog.pg_attribute a ON (NOT a.attisdropped) AND a.attnum > 0 AND a.attrelid = c.oid) INNER JOIN pg_catalog.pg_type t ON t.oid = a.atttypid) LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum ORDER BY n.nspname, c.relname, attnum",
+				tablename,
+				ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
+		} else {
+			snprintf(sql, sizeof(sql), "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM pg_class c, pg_type t, pg_attribute a LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum WHERE c.oid = a.attrelid AND a.atttypid = t.oid AND (a.attnum > 0) AND c.relname = '%s' ORDER BY c.relname, attnum", table);
+		}
+
+		/* Query the columns */
+		result = PQexec(conn, sql);
+		if (PQresultStatus(result) != PGRES_TUPLES_OK) {
+			pgerror = PQresultErrorMessage(result);
+			ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
+			PQclear(result);
+			pgsql_disconnect();
+			return;
+		}
+
+		rows = PQntuples(result);
+		if (rows == 0) {
+			ast_log(LOG_ERROR, "Failed to query database columns. No columns found, does the table exist?\n");
+			PQclear(result);
+			pgsql_disconnect();
+			return;
+		}
+
+		/* Clear out the columns list. */
+		empty_columns();
+
+		for (i = 0; i < rows; i++) {
+			fname = PQgetvalue(result, i, 0);
+			ftype = PQgetvalue(result, i, 1);
+			flen = PQgetvalue(result, i, 2);
+			fnotnull = PQgetvalue(result, i, 3);
+			fdef = PQgetvalue(result, i, 4);
+			if (atoi(flen) == -1) {
+				/* For varchar columns, the maximum length is encoded in a different field */
+				flen = PQgetvalue(result, i, 5);
+			}
+
+			ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
+
+			cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
+			if (cur) {
+				sscanf(flen, "%30d", &cur->len);
+				cur->name = (char *)cur + sizeof(*cur);
+				cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
+				strcpy(cur->name, fname);
+				strcpy(cur->type, ftype);
+				if (*fnotnull == 't') {
+					cur->notnull = 1;
+				} else {
+					cur->notnull = 0;
+				}
+				if (!ast_strlen_zero(fdef)) {
+					cur->hasdefault = 1;
+				} else {
+					cur->hasdefault = 0;
+				}
+				AST_LIST_INSERT_TAIL(&psql_columns, cur, entry);
+			}
+		}
+
+		PQclear(result);
+	} else {
+		pgerror = PQerrorMessage(conn);
+		ast_log(LOG_ERROR, "Unable to connect to database server %s. Events will not be logged!\n", pghostname);
+		ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
+		pgsql_disconnect();
+	}
 }
 
+#define LENGTHEN_BUF(size, var) \
+	do { \
+		/* Lengthen buffer, if necessary */ \
+		if (ast_str_strlen(var) + size + 1 > ast_str_size(var)) { \
+			if (ast_str_make_space(&var, ((ast_str_size(var) + size + 3) / 512 + 1) * 512) != 0) { \
+				ast_log(LOG_ERROR, "Unable to allocate sufficient memory. Insert CEL '%s:%s' failed.\n", pghostname, table); \
+				goto cleanup; \
+			} \
+		} \
+	} while (0)
+
+#define LENGTHEN_BUF1(size) \
+	LENGTHEN_BUF(size, sql1)
+#define LENGTHEN_BUF2(size) \
+	LENGTHEN_BUF(size, sql2)
 
 static void pgsql_log(struct ast_event *event)
 {
-	struct ast_tm tm;
-	char timestr[128];
-	char *pgerror;
 	struct ast_cel_event_record record = {
 		.version = AST_CEL_EVENT_RECORD_VERSION,
 	};
@@ -166,89 +282,86 @@
 
 	ast_mutex_lock(&pgsql_lock);
 
-	ast_localtime(&record.event_time, &tm, NULL);
-	ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
-
-	if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
-		pgsql_reconnect();
-		if (PQstatus(conn) != CONNECTION_BAD) {
-			connected = 1;
-		} else {
-			pgerror = PQerrorMessage(conn);
-			ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
-			ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
-			PQfinish(conn);
-			conn = NULL;
-		}
+	if (!connected) {
+		pgsql_connect();
 	}
+
 	if (connected) {
+		struct ast_tm tm;
 		struct columns *cur;
-		struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
-		char buf[257];
-		char *escapebuf = NULL;
+		struct ast_str *sql1, *sql2;
+		char valbuf[256];
 		const char *value;
-		int first = 1;
-		size_t bufsize = 513;
+		char *separator = "";
+		PGresult *result;
+		char *pgerror;
 
-		escapebuf = ast_malloc(bufsize);
-		if (!escapebuf || !sql || !sql2) {
-			goto ast_log_cleanup;
+		/* Test to be sure we're still connected... */
+		/* If we're connected, and connection is working, good. */
+		/* Otherwise, attempt reconnect.  If it fails... sorry... */
+		PQconsumeInput(conn);
+		if (PQstatus(conn) != CONNECTION_OK) {
+			ast_log(LOG_WARNING, "Connection was lost... attempting to reconnect.\n");
+			pgsql_connect();
+			if (!connected) {
+				ast_mutex_unlock(&pgsql_lock);
+				return;
+			}
 		}
 
-		ast_str_set(&sql, 0, "INSERT INTO %s (", table);
-		ast_str_set(&sql2, 0, " VALUES (");
+		sql1 = ast_str_create(maxsize1);
+		sql2 = ast_str_create(maxsize2);
 
-#define SEP (first ? "" : ",")
+		if (sql1 == NULL || sql2 == NULL) {
+			goto cleanup;
+		}
 
-		AST_RWLIST_RDLOCK(&psql_columns);
-		AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
-			LENGTHEN_BUF1(strlen(cur->name) + 2);
-			ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
+		ast_str_set(&sql1,  0, "INSERT INTO %s (", table);
+		ast_str_set(&sql2, 0, "VALUES (");
 
+		AST_LIST_TRAVERSE(&psql_columns, cur, entry) {
 			if (strcmp(cur->name, "eventtime") == 0) {
 				if (strncmp(cur->type, "int", 3) == 0) {
 					LENGTHEN_BUF2(13);
-					ast_str_append(&sql2, 0, "%s%ld", SEP, (long) record.event_time.tv_sec);
+					ast_str_append(&sql2, 0, "%s%ld", separator, (long) record.event_time.tv_sec);
 				} else if (strncmp(cur->type, "float", 5) == 0) {
 					LENGTHEN_BUF2(31);
-					ast_str_append(&sql2, 0, "%s%f",
-						SEP,
+					ast_str_append(&sql2, 0, "%s%f", separator,
 						(double) record.event_time.tv_sec +
 						(double) record.event_time.tv_usec / 1000000.0);
 				} else {
 					/* char, hopefully */
 					LENGTHEN_BUF2(31);
-					ast_localtime(&record.event_time, &tm, NULL);
-					ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
-					ast_str_append(&sql2, 0, "%s'%s'", SEP, buf);
+					ast_localtime(&record.event_time, &tm, tz);
+					ast_strftime(valbuf, sizeof(valbuf), DATE_FORMAT, &tm);
+					ast_str_append(&sql2, 0, "%s'%s'", separator, valbuf);
 				}
 			} else if (strcmp(cur->name, "eventtype") == 0) {
-				if (cur->type[0] == 'i') {
+				if (strncmp(cur->type, "int", 3) == 0) {
 					/* Get integer, no need to escape anything */
 					LENGTHEN_BUF2(5);
-					ast_str_append(&sql2, 0, "%s%d", SEP, (int) record.event_type);
+					ast_str_append(&sql2, 0, "%s%d", separator, (int) record.event_type);
 				} else if (strncmp(cur->type, "float", 5) == 0) {
 					LENGTHEN_BUF2(31);
-					ast_str_append(&sql2, 0, "%s%f", SEP, (double) record.event_type);
+					ast_str_append(&sql2, 0, "%s%f", separator, (double) record.event_type);
 				} else {
 					/* Char field, probably */
 					const char *event_name;
 
-					event_name = (!cel_show_user_def
-						&& record.event_type == AST_CEL_USER_DEFINED)
+					event_name = (!cel_show_user_def && record.event_type == AST_CEL_USER_DEFINED)
 						? record.user_defined_name : record.event_name;
-					LENGTHEN_BUF2(strlen(event_name) + 1);
-					ast_str_append(&sql2, 0, "%s'%s'", SEP, event_name);
+					LENGTHEN_BUF2(strlen(event_name) + 3);
+					ast_str_append(&sql2, 0, "%s'%s'", separator, event_name);
 				}
 			} else if (strcmp(cur->name, "amaflags") == 0) {
 				if (strncmp(cur->type, "int", 3) == 0) {
 					/* Integer, no need to escape anything */
 					LENGTHEN_BUF2(13);
-					ast_str_append(&sql2, 0, "%s%u", SEP, record.amaflag);
+					ast_str_append(&sql2, 0, "%s%u", separator, record.amaflag);
 				} else {
 					/* Although this is a char field, there are no special characters in the values for these fields */
 					LENGTHEN_BUF2(31);
-					ast_str_append(&sql2, 0, "%s'%u'", SEP, record.amaflag);
+					ast_str_append(&sql2, 0, "%s'%u'", separator, record.amaflag);
 				}
 			} else {
 				/* Arbitrary field, could be anything */
@@ -292,366 +405,287 @@
 					value = NULL;
 				}
 
-				if (value == NULL) {
-					ast_str_append(&sql2, 0, "%sDEFAULT", SEP);
-				} else if (strncmp(cur->type, "int", 3) == 0) {
-					long long whatever;
-					if (value && sscanf(value, "%30lld", &whatever) == 1) {
-						LENGTHEN_BUF2(26);
-						ast_str_append(&sql2, 0, "%s%lld", SEP, whatever);
-					} else {
-						LENGTHEN_BUF2(2);
-						ast_str_append(&sql2, 0, "%s0", SEP);
-					}
-				} else if (strncmp(cur->type, "float", 5) == 0) {
-					long double whatever;
-					if (value && sscanf(value, "%30Lf", &whatever) == 1) {
-						LENGTHEN_BUF2(51);
-						ast_str_append(&sql2, 0, "%s%30Lf", SEP, whatever);
+				if (value) {
+					if (strncmp(cur->type, "int", 3) == 0) {
+						long long whatever;
+						if (sscanf(value, "%30lld", &whatever) == 1) {
+							LENGTHEN_BUF2(26);
+							ast_str_append(&sql2, 0, "%s%lld", separator, whatever);
+						} else {
+							value = NULL;
+						}
+					} else if (strncmp(cur->type, "float", 5) == 0) {
+						long double whatever;
+						if (sscanf(value, "%30Lf", &whatever) == 1) {
+							LENGTHEN_BUF2(51);
+							ast_str_append(&sql2, 0, "%s%30Lf", separator, whatever);
+						} else {
+							value = NULL;
+						}
 					} else {
-						LENGTHEN_BUF2(2);
-						ast_str_append(&sql2, 0, "%s0", SEP);
+						size_t len = strlen(value);
+						char *escapebuf = ast_alloca(len * 2 + 1);
+						len = PQescapeStringConn(conn, escapebuf, value, len, NULL);
+						LENGTHEN_BUF2(len + 3);
+						ast_str_append(&sql2, 0, "%s'%s'", separator, escapebuf);
 					}
-					/* XXX Might want to handle dates, times, and other misc fields here XXX */
-				} else {
-					if (value) {
-						size_t required_size = strlen(value) * 2 + 1;
-
-						/* If our argument size exceeds our buffer, grow it,
-						 * as PQescapeStringConn() expects the buffer to be
-						 * adequitely sized and does *NOT* do size checking.
-						 */
-						if (required_size > bufsize) {
-							char *tmpbuf = ast_realloc(escapebuf, required_size);
-
-							if (!tmpbuf) {
-								AST_RWLIST_UNLOCK(&psql_columns);
-								goto ast_log_cleanup;
-							}
+				}
 
-							escapebuf = tmpbuf;
-							bufsize = required_size;
+				if (value == NULL) {
+					if (cur->notnull && !cur->hasdefault) {
+						if (strncmp(cur->type, "int", 3) == 0 || strncmp(cur->type, "float", 5) == 0) {
+							LENGTHEN_BUF2(2);
+							ast_str_append(&sql2, 0, "%s0", separator);
+						} else {
+							LENGTHEN_BUF2(3);
+							ast_str_append(&sql2, 0, "%s''", separator);
 						}
-						PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
 					} else {
-						escapebuf[0] = '\0';
+						continue;
 					}
-					LENGTHEN_BUF2(strlen(escapebuf) + 3);
-					ast_str_append(&sql2, 0, "%s'%s'", SEP, escapebuf);
 				}
 			}
-			first = 0;
-		}
-		AST_RWLIST_UNLOCK(&psql_columns);
-		LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
-		ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
 
-		ast_debug(3, "Inserting a CEL record: [%s].\n", ast_str_buffer(sql));
-		/* Test to be sure we're still connected... */
-		/* If we're connected, and connection is working, good. */
-		/* Otherwise, attempt reconnect.  If it fails... sorry... */
-		if (PQstatus(conn) == CONNECTION_OK) {
-			connected = 1;
-		} else {
-			ast_log(LOG_WARNING, "Connection was lost... attempting to reconnect.\n");
-			PQreset(conn);
-			if (PQstatus(conn) == CONNECTION_OK) {
-				ast_log(LOG_NOTICE, "Connection reestablished.\n");
-				connected = 1;
-			} else {
-				pgerror = PQerrorMessage(conn);
-				ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
-				ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
-				PQfinish(conn);
-				conn = NULL;
-				connected = 0;
-				goto ast_log_cleanup;
-			}
+			LENGTHEN_BUF1(strlen(cur->name) + 3);
+			ast_str_append(&sql1, 0, "%s\"%s\"", separator, cur->name);
+			separator = ",";
 		}
-		result = PQexec(conn, ast_str_buffer(sql));
+
+		LENGTHEN_BUF1(ast_str_strlen(sql2) + 3);
+		ast_str_append(&sql1, 0, ") %s)", ast_str_buffer(sql2));
+
+		ast_debug(3, "Inserting record: [%s].\n", ast_str_buffer(sql1));
+
+		result = PQexec(conn, ast_str_buffer(sql1));
 		if (PQresultStatus(result) != PGRES_COMMAND_OK) {
 			pgerror = PQresultErrorMessage(result);
-			ast_log(LOG_WARNING, "Failed to insert call detail record into database!\n");
+			ast_log(LOG_WARNING, "Failed insert record into database!\n");
 			ast_log(LOG_WARNING, "Reason: %s\n", pgerror);
 			ast_log(LOG_WARNING, "Connection may have been lost... attempting to reconnect.\n");
 			PQreset(conn);
 			if (PQstatus(conn) == CONNECTION_OK) {
 				ast_log(LOG_NOTICE, "Connection reestablished.\n");
-				connected = 1;
 				PQclear(result);
-				result = PQexec(conn, ast_str_buffer(sql));
+				result = PQexec(conn, ast_str_buffer(sql1));
 				if (PQresultStatus(result) != PGRES_COMMAND_OK) {
 					pgerror = PQresultErrorMessage(result);
-					ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
+					ast_log(LOG_ERROR, "HARD ERROR! DROPPING RECORD!\n");
 					ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
+					pgsql_disconnect();
 				}
+			} else {
+				pgerror = PQerrorMessage(conn);
+				ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Event will not be logged!\n", pghostname);
+				ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
+				pgsql_disconnect();
 			}
 		}
 		PQclear(result);
 
-ast_log_cleanup:
-		ast_free(sql);
+		/* Next time, just allocate buffers that are that big to start with. */
+		if (ast_str_strlen(sql1) > maxsize1) {
+			maxsize1 = ast_str_strlen(sql1);
+		}
+		if (ast_str_strlen(sql2) > maxsize2) {
+			maxsize2 = ast_str_strlen(sql2);
+		}
+
+cleanup:
+		ast_free(sql1);
 		ast_free(sql2);
-		ast_free(escapebuf);
 	}
 
 	ast_mutex_unlock(&pgsql_lock);
 }
 
-static int my_unload_module(void)
+static int config_module(int reload)
 {
-	struct columns *current;
+	const char *tmp;
+	struct ast_config *cfg;
+	struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
 
-	ast_cel_backend_unregister(PGSQL_BACKEND_NAME);
-	AST_RWLIST_WRLOCK(&psql_columns);
-	if (conn) {
-		PQfinish(conn);
-		conn = NULL;
-	}
-	if (pghostname) {
-		ast_free(pghostname);
-		pghostname = NULL;
-	}
-	if (pgdbname) {
-		ast_free(pgdbname);
-		pgdbname = NULL;
-	}
-	if (pgdbuser) {
-		ast_free(pgdbuser);
-		pgdbuser = NULL;
-	}
-	if (pgpassword) {
-		ast_free(pgpassword);
-		pgpassword = NULL;
-	}
-	if (pgappname) {
-		ast_free(pgappname);
-		pgappname = NULL;
-	}
-	if (pgdbport) {
-		ast_free(pgdbport);
-		pgdbport = NULL;
-	}
-	if (table) {
-		ast_free(table);
-		table = NULL;
-	}
-	while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
-		ast_free(current);
+	if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
+		ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CEL's: %s\n", config);
+		return -1;
+	} else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
+		return 0;
 	}
-	AST_RWLIST_UNLOCK(&psql_columns);
-	return 0;
-}
-
-static int unload_module(void)
-{
-	return my_unload_module();
-}
 
-static int process_my_load_module(struct ast_config *cfg)
-{
-	struct ast_variable *var;
-	char *pgerror;
-	const char *tmp;
-	PGresult *result;
-	struct columns *cur;
+	ast_mutex_lock(&pgsql_lock);
 
-	if (!(var = ast_variable_browse(cfg, "global"))) {
-		ast_log(LOG_WARNING,"CEL pgsql config file missing global section.\n");
-		return AST_MODULE_LOAD_DECLINE;
+	if (!ast_variable_browse(cfg, "global")) {
+		ast_log(LOG_NOTICE, "%s config file missing global section, skipping module %s.\n",
+			config, reload ? "reload" : "load");
+		goto err;
 	}
+
 	if (!(tmp = ast_variable_retrieve(cfg,"global","hostname"))) {
-		ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
+		ast_log(LOG_WARNING,"PostgreSQL server hostname not specified. Assuming unix socket connection\n");
 		tmp = "";	/* connect via UNIX-socket by default */
 	}
-	if (pghostname)
-		ast_free(pghostname);
+	ast_free(pghostname);
 	if (!(pghostname = ast_strdup(tmp))) {
-		ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying host info\n");
-		return AST_MODULE_LOAD_DECLINE;
+		ast_log(LOG_WARNING,"Insufficient memory for copying hostname info\n\n");
+		goto err;
+	}
+
+	if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
+		ast_log(LOG_WARNING,"PostgreSQL database port not specified. Using default 5432.\n");
+		tmp = "5432";
 	}
+	ast_free(pgdbport);
+	if (!(pgdbport = ast_strdup(tmp))) {
+		ast_log(LOG_WARNING,"Insufficient memory for copying port info\n");
+		goto err;
+	}
+
 	if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
-		ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
-		tmp = "asteriskceldb";
+		ast_log(LOG_WARNING,"PostgreSQL database not specified. Assuming asterisk\n");
+		tmp = "asterisk";
 	}
-	if (pgdbname)
-		ast_free(pgdbname);
+	ast_free(pgdbname);
 	if (!(pgdbname = ast_strdup(tmp))) {
-		ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying dbname info\n");
-		return AST_MODULE_LOAD_DECLINE;
+		ast_log(LOG_WARNING,"Insufficient memory for copying dbname info\n");
+		goto err;
 	}
+
 	if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
-		ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming asterisk\n");
+		ast_log(LOG_WARNING,"PostgreSQL database user not specified. Assuming asterisk\n");
 		tmp = "asterisk";
 	}
-	if (pgdbuser)
-		ast_free(pgdbuser);
+	ast_free(pgdbuser);
 	if (!(pgdbuser = ast_strdup(tmp))) {
-		ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying user info\n");
-		return AST_MODULE_LOAD_DECLINE;
+		ast_log(LOG_WARNING,"Insufficient memory for copying user info\n");
+		goto err;
 	}
+
 	if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
-		ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
+		ast_log(LOG_WARNING, "PostgreSQL database password not specified. Assuming blank\n");
 		tmp = "";
 	}
-	if (pgpassword)
-		ast_free(pgpassword);
+	ast_free(pgpassword);
 	if (!(pgpassword = ast_strdup(tmp))) {
-		ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying password info\n");
-		return AST_MODULE_LOAD_DECLINE;
+		ast_log(LOG_WARNING,"Insufficient memory for copying password info\n");
+		goto err;
 	}
+
+	if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
+		ast_log(LOG_WARNING,"CEL table not specified. Assuming cel\n");
+		tmp = "cel";
+	}
+	ast_free(table);
+	if (!(table = ast_strdup(tmp))) {
+		ast_log(LOG_WARNING,"Insufficient memory for copying table info\n");
+		goto err;
+	}
+
 	if (!(tmp = ast_variable_retrieve(cfg, "global", "appname"))) {
 		tmp = "";
 	}
-	if (pgappname) {
-		ast_free(pgappname);
-	}
+	ast_free(pgappname);
 	if (!(pgappname = ast_strdup(tmp))) {
-		ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying appname info\n");
-		return AST_MODULE_LOAD_DECLINE;
+		ast_log(LOG_WARNING,"Insufficient memory for copying appname info\n");
+		goto err;
 	}
 
-	if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
-		ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
-		tmp = "5432";
+	if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
+		ast_log(LOG_WARNING, "Encoding not specified. Assuming UTF8\n");
+		tmp = "UTF8";
 	}
-	if (pgdbport)
-		ast_free(pgdbport);
-	if (!(pgdbport = ast_strdup(tmp))) {
-		ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying port info\n");
-		return AST_MODULE_LOAD_DECLINE;
+	ast_free(encoding);
+	if (!(encoding = ast_strdup(tmp))) {
+		ast_log(LOG_WARNING,"Insufficient memory for copying encoding info\n");
+		goto err;
 	}
-	if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
-		ast_log(LOG_WARNING,"CEL table not specified.  Assuming cel\n");
-		tmp = "cel";
+
+	if (!(tmp = ast_variable_retrieve(cfg, "global", "timezone"))) {
+		tmp = "";
 	}
-	if (table)
-		ast_free(table);
-	if (!(table = ast_strdup(tmp))) {
-		return AST_MODULE_LOAD_DECLINE;
+	ast_free(tz);
+	tz = NULL;
+	if (!ast_strlen_zero(tmp) && !(tz = ast_strdup(tmp))) {
+		ast_log(LOG_WARNING,"Insufficient memory for copying timezone info\n");
+		goto err;
 	}
+
 	cel_show_user_def = CEL_SHOW_USERDEF_DEFAULT;
 	if ((tmp = ast_variable_retrieve(cfg, "global", "show_user_defined"))) {
 		cel_show_user_def = ast_true(tmp) ? 1 : 0;
 	}
+
 	if (option_debug) {
 		if (ast_strlen_zero(pghostname)) {
-			ast_debug(3, "cel_pgsql: using default unix socket\n");
+			ast_debug(3, "Using default unix socket\n");
 		} else {
-			ast_debug(3, "cel_pgsql: got hostname of %s\n", pghostname);
+			ast_debug(3, "Got hostname of %s\n", pghostname);
 		}
-		ast_debug(3, "cel_pgsql: got port of %s\n", pgdbport);
-		ast_debug(3, "cel_pgsql: got user of %s\n", pgdbuser);
-		ast_debug(3, "cel_pgsql: got dbname of %s\n", pgdbname);
-		ast_debug(3, "cel_pgsql: got password of %s\n", pgpassword);
-		ast_debug(3, "cel_pgsql: got sql table name of %s\n", table);
-		ast_debug(3, "cel_pgsql: got show_user_defined of %s\n",
+		ast_debug(3, "Got port of %s\n", pgdbport);
+		ast_debug(3, "Got dbname of %s\n", pgdbname);
+		ast_debug(3, "Got user of %s\n", pgdbuser);
+		ast_debug(3, "Got password of %s\n", pgpassword);
+		ast_debug(3, "Got table name of %s\n", table);
+		ast_debug(3, "Got application name of %s\n", pgappname);
+		ast_debug(3, "Got encoding of %s\n", encoding);
+		ast_debug(3, "Got timezone of %s\n", tz);
+		ast_debug(3, "Got show_user_defined of %s\n",
 			cel_show_user_def ? "Yes" : "No");
 	}
 
-	pgsql_reconnect();
-	if (PQstatus(conn) != CONNECTION_BAD) {
-		char sqlcmd[512];
-		char *fname, *ftype, *flen, *fnotnull, *fdef;
-		char *tableptr;
-		int i, rows;
-
-		ast_debug(1, "Successfully connected to PostgreSQL database.\n");
-		connected = 1;
-
-		/* Remove any schema name from the table */
-		if ((tableptr = strrchr(table, '.'))) {
-			tableptr++;
-		} else {
-			tableptr = table;
-		}
+	pgsql_connect();
 
-		/* Query the columns */
-		snprintf(sqlcmd, sizeof(sqlcmd), "select a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc from pg_class c, pg_type t, pg_attribute a left outer join pg_attrdef d on a.atthasdef and d.adrelid = a.attrelid and d.adnum = a.attnum where c.oid = a.attrelid and a.atttypid = t.oid and (a.attnum > 0) and c.relname = '%s' order by c.relname, attnum", tableptr);
-		result = PQexec(conn, sqlcmd);
-		if (PQresultStatus(result) != PGRES_TUPLES_OK) {
-			pgerror = PQresultErrorMessage(result);
-			ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
-			PQclear(result);
-			unload_module();
-			return AST_MODULE_LOAD_DECLINE;
-		}
+	ast_mutex_unlock(&pgsql_lock);
+	ast_config_destroy(cfg);
+	return 0;
 
-		rows = PQntuples(result);
-		for (i = 0; i < rows; i++) {
-			fname = PQgetvalue(result, i, 0);
-			ftype = PQgetvalue(result, i, 1);
-			flen = PQgetvalue(result, i, 2);
-			fnotnull = PQgetvalue(result, i, 3);
-			fdef = PQgetvalue(result, i, 4);
-			ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
-			cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
-			if (cur) {
-				sscanf(flen, "%30d", &cur->len);
-				cur->name = (char *)cur + sizeof(*cur);
-				cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
-				strcpy(cur->name, fname);
-				strcpy(cur->type, ftype);
-				if (*fnotnull == 't') {
-					cur->notnull = 1;
-				} else {
-					cur->notnull = 0;
-				}
-				if (!ast_strlen_zero(fdef)) {
-					cur->hasdefault = 1;
-				} else {
-					cur->hasdefault = 0;
-				}
-				AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
-			}
-		}
-		PQclear(result);
-	} else {
-		pgerror = PQerrorMessage(conn);
-		ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
-		ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
-		connected = 0;
-		PQfinish(conn);
-		conn = NULL;
-	}
-	return AST_MODULE_LOAD_SUCCESS;
+err:
+	ast_mutex_unlock(&pgsql_lock);
+	ast_config_destroy(cfg);
+	return -1;
 }
 
-static int my_load_module(int reload)
+static int load_module(void)
 {
-	struct ast_config *cfg;
-	struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
-
-	if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
-		ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CEL's: %s\n", config);
+	if (config_module(0)) {
 		return AST_MODULE_LOAD_DECLINE;
-	} else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
-		return AST_MODULE_LOAD_SUCCESS;
 	}
 
-	if (reload) {
-		my_unload_module();
+	if (ast_cel_backend_register(name, pgsql_log)) {
+		return AST_MODULE_LOAD_DECLINE;
 	}
 
-	process_my_load_module(cfg);
-	ast_config_destroy(cfg);
+	return AST_MODULE_LOAD_SUCCESS;
+}
 
-	if (ast_cel_backend_register(PGSQL_BACKEND_NAME, pgsql_log)) {
-		ast_log(LOG_WARNING, "Unable to subscribe to CEL events for pgsql\n");
+static int reload(void)
+{
+	if (config_module(1)) {
 		return AST_MODULE_LOAD_DECLINE;
 	}
 
 	return AST_MODULE_LOAD_SUCCESS;
 }
 
-static int load_module(void)
+static int unload_module(void)
 {
-	return my_load_module(0);
-}
+	if (ast_cel_backend_unregister(name)) {
+		return -1;
+	}
 
-static int reload(void)
-{
-	return my_load_module(1);
+	pgsql_disconnect();
+
+	ast_free(pghostname);
+	ast_free(pgdbport);
+	ast_free(pgdbname);
+	ast_free(pgdbuser);
+	ast_free(pgpassword);
+	ast_free(table);
+	ast_free(pgappname);
+	ast_free(encoding);
+	ast_free(tz);
+
+	empty_columns();
+
+	return 0;
 }
 
 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CEL Backend",
--- configs/samples/cel_pgsql.conf.sample.orig2
+++ configs/samples/cel_pgsql.conf.sample
@@ -7,31 +7,23 @@
 ; CEL field names:
 ;
 ;	eventtype
-;	  CHANNEL_START = 1
-;	  CHANNEL_END = 2
+;	  CHAN_START = 1
+;	  CHAN_END = 2
 ;	  HANGUP = 3
 ;	  ANSWER = 4
 ;	  APP_START = 5
 ;	  APP_END = 6
-;	  BRIDGE_START = 7
-;	  BRIDGE_END = 8
-;	  CONF_START = 9
-;	  CONF_END = 10
-;	  PARK_START = 11
-;	  PARK_END = 12
-;	  BLINDTRANSFER = 13
-;	  ATTENDEDTRANSFER = 14
-;	  TRANSFER = 15
-;	  HOOKFLASH = 16
-;	  3WAY_START = 17
-;	  3WAY_END = 18
-;	  CONF_ENTER = 19
-;	  CONF_EXIT = 20
-;	  USER_DEFINED = 21
-;	  LINKEDID_END = 22
-;	  BRIDGE_UPDATE = 23
-;	  PICKUP = 24
-;	  FORWARD = 25
+;	  BRIDGE_ENTER = 7
+;	  BRIDGE_EXIT = 8
+;	  PARK_START = 9
+;	  PARK_END = 10
+;	  BLINDTRANSFER = 11
+;	  ATTENDEDTRANSFER = 12
+;	  USER_DEFINED = 13
+;	  LINKEDID_END = 14
+;	  PICKUP = 15
+;	  FORWARD = 16
+;	  LOCAL_OPTIMIZE = 17
 ;	eventtime  (timeval, includes microseconds)
 ;	userdeftype (set only if eventtype == USER_DEFINED)
 ;	cid_name
@@ -62,7 +54,9 @@
 ;hostname=localhost
 ;port=5432
 ;dbname=asterisk
-;password=password
 ;user=postgres
-;table=cel		;SQL table where CEL's will be inserted
-;appname=asterisk   ; Postgres application_name support (optional). Whitespace not allowed.
\ No newline at end of file
+;password=password
+;table=cel		; SQL table where CEL's will be inserted
+;appname=asterisk	; Postgres application_name support (optional). Whitespace not allowed.
+;encoding=UTF8		; Encoding of logged characters in Asterisk
+;timezone=UTC		; Uncomment if you want eventtime fields in UTC/GMT
