More 32->64 bit codec conversions.
[asterisk/asterisk.git] / channels / chan_skinny.c
index 8263a79..79eb2fb 100644 (file)
@@ -49,11 +49,12 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/pbx.h"
 #include "asterisk/sched.h"
 #include "asterisk/io.h"
-#include "asterisk/rtp.h"
+#include "asterisk/rtp_engine.h"
 #include "asterisk/netsock.h"
 #include "asterisk/acl.h"
 #include "asterisk/callerid.h"
 #include "asterisk/cli.h"
+#include "asterisk/manager.h"
 #include "asterisk/say.h"
 #include "asterisk/cdr.h"
 #include "asterisk/astdb.h"
@@ -68,6 +69,71 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/devicestate.h"
 #include "asterisk/event.h"
 #include "asterisk/indications.h"
+#include "asterisk/linkedlists.h"
+
+/*** DOCUMENTATION
+       <manager name="SKINNYdevices" language="en_US">
+               <synopsis>
+                       List SKINNY devices (text format).
+               </synopsis>
+               <syntax>
+                       <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
+               </syntax>
+               <description>
+                       <para>Lists Skinny devices in text format with details on current status.
+                       Devicelist will follow as separate events, followed by a final event called
+                       DevicelistComplete.</para>
+               </description>
+       </manager>
+       <manager name="SKINNYshowdevice" language="en_US">
+               <synopsis>
+                       Show SKINNY device (text format).
+               </synopsis>
+               <syntax>
+                       <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
+                       <parameter name="Device" required="true">
+                               <para>The device name you want to check.</para>
+                       </parameter>
+               </syntax>
+               <description>
+                       <para>Show one SKINNY device with details on current status.</para>
+               </description>
+       </manager>
+       <manager name="SKINNYlines" language="en_US">
+               <synopsis>
+                       List SKINNY lines (text format).
+               </synopsis>
+               <syntax>
+                       <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
+               </syntax>
+               <description>
+                       <para>Lists Skinny lines in text format with details on current status.
+                       Linelist will follow as separate events, followed by a final event called
+                       LinelistComplete.</para>
+               </description>
+       </manager>
+       <manager name="SKINNYshowline" language="en_US">
+               <synopsis>
+                       Show SKINNY line (text format).
+               </synopsis>
+               <syntax>
+                       <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
+                       <parameter name="Line" required="true">
+                               <para>The line name you want to check.</para>
+                       </parameter>
+               </syntax>
+               <description>
+                       <para>Show one SKINNY line with details on current status.</para>
+               </description>
+       </manager>
+ ***/
+
+#ifdef SKINNY_DEVMODE
+#define SKINNY_DEVONLY(code)   \
+       code
+#else
+#define SKINNY_DEVONLY(code)
+#endif
 
 /*************************************
  * Skinny/Asterisk Protocol Settings *
@@ -75,7 +141,7 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 static const char tdesc[] = "Skinny Client Control Protocol (Skinny)";
 static const char config[] = "skinny.conf";
 
-static int default_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW;
+static format_t default_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW;
 static struct ast_codec_pref default_prefs;
 
 enum skinny_codecs {
@@ -92,15 +158,17 @@ enum skinny_codecs {
 #define DEFAULT_SKINNY_BACKLOG 2
 #define SKINNY_MAX_PACKET 1000
 
-static unsigned int tos = 0;
-static unsigned int tos_audio = 0;
-static unsigned int tos_video = 0;
-static unsigned int cos = 0;
-static unsigned int cos_audio = 0;
-static unsigned int cos_video = 0;
+static struct {
+       unsigned int tos;
+       unsigned int tos_audio;
+       unsigned int tos_video;
+       unsigned int cos;
+       unsigned int cos_audio;
+       unsigned int cos_video;
+} qos = { 0, 0, 0, 0, 0, 0 };
 
 static int keep_alive = 120;
-static char vmexten[AST_MAX_EXTENSION];      /* Voicemail pilot number */
+static char global_vmexten[AST_MAX_EXTENSION];      /* Voicemail pilot number */
 static char used_context[AST_MAX_EXTENSION]; /* placeholder to check if context are already used in regcontext */
 static char regcontext[AST_MAX_CONTEXT];     /* Context for auto-extension */
 static char date_format[6] = "D-M-Y";
@@ -156,6 +224,11 @@ static struct ast_jb_conf default_jbconf =
 };
 static struct ast_jb_conf global_jbconf;
 
+#ifdef SKINNY_DEVMODE
+AST_THREADSTORAGE(message2str_threadbuf);
+#define MESSAGE2STR_BUFSIZE   35
+#endif
+
 AST_THREADSTORAGE(device2str_threadbuf);
 #define DEVICE2STR_BUFSIZE   15
 
@@ -569,7 +642,7 @@ struct soft_key_template_definition {
 #define SOFTKEY_DND 0x13
 #define SOFTKEY_IDIVERT 0x14
 
-struct soft_key_template_definition soft_key_template_default[] = {
+static struct soft_key_template_definition soft_key_template_default[] = {
        { "\200\001", SOFTKEY_REDIAL },
        { "\200\002", SOFTKEY_NEWCALL },
        { "\200\003", SOFTKEY_HOLD },
@@ -947,49 +1020,25 @@ struct skinny_req {
 /* XXX This is the combined size of the variables above.  (len, res, e)
    If more are added, this MUST change.
    (sizeof(skinny_req) - sizeof(skinny_data)) DOES NOT WORK on all systems (amd64?). */
-int skinny_header_size = 12;
+static int skinny_header_size = 12;
 
 /*****************************
  * Asterisk specific globals *
  *****************************/
 
 static int skinnydebug = 0;
+static int skinnyreload = 0;
 
 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
 static struct sockaddr_in bindaddr;
 static char ourhost[256];
 static int ourport;
 static struct in_addr __ourip;
-struct ast_hostent ahp;
-struct hostent *hp;
+static struct ast_hostent ahp;
+static struct hostent *hp;
 static int skinnysock = -1;
 static pthread_t accept_t;
-static char context[AST_MAX_CONTEXT] = "default";
-static char language[MAX_LANGUAGE] = "";
-static char mohinterpret[MAX_MUSICCLASS] = "default";
-static char mohsuggest[MAX_MUSICCLASS] = "";
-static char cid_num[AST_MAX_EXTENSION] = "";
-static char cid_name[AST_MAX_EXTENSION] = "";
-static char linelabel[AST_MAX_EXTENSION] ="";
-static char parkinglot[AST_MAX_CONTEXT] ="";
-static int nat = 0;
-static ast_group_t cur_callergroup = 0;
-static ast_group_t cur_pickupgroup = 0;
-static int immediate = 0;
-static int callwaiting = 0;
-static int callreturn = 0;
-static int threewaycalling = 0;
-static int mwiblink = 0;
-/* This is for flashhook transfers */
-static int transfer = 0;
-static int cancallforward = 0;
-/* static int busycount = 3;*/
-static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
-static char mailbox[AST_MAX_EXTENSION];
-static char regexten[AST_MAX_EXTENSION];
-static int amaflags = 0;
 static int callnums = 1;
-static int canreinvite = 0;
 
 #define SKINNY_DEVICE_UNKNOWN -1
 #define SKINNY_DEVICE_NONE 0
@@ -1074,9 +1123,6 @@ static int canreinvite = 0;
 #define SKINNY_CFWD_BUSY      (1 << 1)
 #define SKINNY_CFWD_NOANSWER  (1 << 2)
 
-#define TYPE_TRUNK 1
-#define TYPE_LINE 2
-
 /* Skinny rtp stream modes. Do we really need this? */
 #define SKINNY_CX_SENDONLY 0
 #define SKINNY_CX_RECVONLY 1
@@ -1087,7 +1133,7 @@ static int canreinvite = 0;
 #define SKINNY_CX_INACTIVE 4
 
 #if 0
-static char *skinny_cxmodes[] = {
+static const char * const skinny_cxmodes[] = {
        "sendonly",
        "recvonly",
        "sendrecv",
@@ -1105,10 +1151,6 @@ static struct io_context *io;
 AST_MUTEX_DEFINE_STATIC(monlock);
 /* Protect the network socket */
 AST_MUTEX_DEFINE_STATIC(netlock);
-/* Protect the session list */
-AST_MUTEX_DEFINE_STATIC(sessionlock);
-/* Protect the device list */
-AST_MUTEX_DEFINE_STATIC(devicelock);
 
 /* This is the thread for the monitor which checks for input on the channels
    which are not currently in use. */
@@ -1126,8 +1168,8 @@ static int matchdigittimeout = 3000;
 struct skinny_subchannel {
        ast_mutex_t lock;
        struct ast_channel *owner;
-       struct ast_rtp *rtp;
-       struct ast_rtp *vrtp;
+       struct ast_rtp_instance *rtp;
+       struct ast_rtp_instance *vrtp;
        unsigned int callid;
        /* time_t lastouttime; */ /* Unused */
        int progress;
@@ -1142,70 +1184,100 @@ struct skinny_subchannel {
        int xferor;
 
 
-       struct skinny_subchannel *next;
+       AST_LIST_ENTRY(skinny_subchannel) list;
        struct skinny_subchannel *related;
        struct skinny_line *parent;
 };
 
+#define SKINNY_LINE_OPTIONS                            \
+       char name[80];                                  \
+       char label[24];                                 \
+       char accountcode[AST_MAX_ACCOUNT_CODE];         \
+       char exten[AST_MAX_EXTENSION];                  \
+       char context[AST_MAX_CONTEXT];                  \
+       char language[MAX_LANGUAGE];                    \
+       char cid_num[AST_MAX_EXTENSION];                \
+       char cid_name[AST_MAX_EXTENSION];               \
+       char lastcallerid[AST_MAX_EXTENSION];           \
+       int cfwdtype;                                   \
+       char call_forward_all[AST_MAX_EXTENSION];       \
+       char call_forward_busy[AST_MAX_EXTENSION];      \
+       char call_forward_noanswer[AST_MAX_EXTENSION];  \
+       char mailbox[AST_MAX_EXTENSION];                \
+       char vmexten[AST_MAX_EXTENSION];                \
+       char regexten[AST_MAX_EXTENSION];               \
+       char regcontext[AST_MAX_CONTEXT];               \
+       char parkinglot[AST_MAX_CONTEXT];               \
+       char mohinterpret[MAX_MUSICCLASS];              \
+       char mohsuggest[MAX_MUSICCLASS];                \
+       char lastnumberdialed[AST_MAX_EXTENSION];       \
+       int curtone;                                    \
+       ast_group_t callgroup;                          \
+       ast_group_t pickupgroup;                        \
+       int callwaiting;                                \
+       int transfer;                                   \
+       int threewaycalling;                            \
+       int mwiblink;                                   \
+       int cancallforward;                             \
+       int getforward;                                 \
+       int callreturn;                                 \
+       int dnd;                                        \
+       int hascallerid;                                \
+       int hidecallerid;                               \
+       int amaflags;                                   \
+       int type;                                       \
+       int instance;                                   \
+       int group;                                      \
+       int needdestroy;                                \
+       format_t confcapability;                                \
+       struct ast_codec_pref confprefs;                \
+       format_t capability;                                    \
+       struct ast_codec_pref prefs;                    \
+       int nonCodecCapability;                         \
+       int onhooktime;                                 \
+       int msgstate;                                   \
+       int immediate;                                  \
+       int hookstate;                                  \
+       int nat;                                        \
+       int directmedia;                                \
+       int prune;
+
 struct skinny_line {
+       SKINNY_LINE_OPTIONS
        ast_mutex_t lock;
-       char name[80];
-       char label[24]; /* Label that shows next to the line buttons */
-       char accountcode[AST_MAX_ACCOUNT_CODE];
-       char exten[AST_MAX_EXTENSION]; /* Extension where to start */
-       char context[AST_MAX_CONTEXT];
-       char language[MAX_LANGUAGE];
-       char cid_num[AST_MAX_EXTENSION]; /* Caller*ID */
-       char cid_name[AST_MAX_EXTENSION]; /* Caller*ID */
-       char lastcallerid[AST_MAX_EXTENSION]; /* Last Caller*ID */
-       int cfwdtype;
-       char call_forward_all[AST_MAX_EXTENSION];
-       char call_forward_busy[AST_MAX_EXTENSION];
-       char call_forward_noanswer[AST_MAX_EXTENSION];
-       char mailbox[AST_MAX_EXTENSION];
-       char vmexten[AST_MAX_EXTENSION];
-       char regexten[AST_MAX_EXTENSION]; /* Extension for auto-extensions */
-       char regcontext[AST_MAX_CONTEXT]; /* Context for auto-extensions */
-       char parkinglot[AST_MAX_CONTEXT]; /* Parkinglot for parkedcalls */
-       char mohinterpret[MAX_MUSICCLASS];
-       char mohsuggest[MAX_MUSICCLASS];
-       char lastnumberdialed[AST_MAX_EXTENSION]; /* Last number that was dialed - used for redial */
-       int curtone; /* Current tone being played */
-       ast_group_t callgroup;
-       ast_group_t pickupgroup;
        struct ast_event_sub *mwi_event_sub; /* Event based MWI */
-       int callwaiting;
-       int transfer;
-       int threewaycalling;
-       int mwiblink;
-       int cancallforward;
-       int getforward;
-       int callreturn;
-       int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
-       int hascallerid;
-       int hidecallerid;
-       int amaflags;
-       int type;
-       int instance;
-       int group;
-       int needdestroy;
-       int capability;
-       int nonCodecCapability;
-       int onhooktime;
-       int msgstate; /* voicemail message state */
-       int immediate;
-       int hookstate;
-       int nat;
-       int canreinvite;
-
-       struct ast_codec_pref prefs;
-       struct skinny_subchannel *sub;
        struct skinny_subchannel *activesub;
-       struct skinny_line *next;
-       struct skinny_device *parent;
+       AST_LIST_HEAD(, skinny_subchannel) sub;
+       AST_LIST_ENTRY(skinny_line) list;
+       AST_LIST_ENTRY(skinny_line) all;
+       struct skinny_device *device;
        struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
+       int newmsgs;
 };
 
+static struct skinny_line_options{
+       SKINNY_LINE_OPTIONS
+} default_line_struct = {
+       .callwaiting = 1,
+       .transfer = 1,
+       .mwiblink = 0,
+       .dnd = 0,
+       .hidecallerid = 0,
+       .amaflags = 0,
+       .instance = 0,
+       .directmedia = 0,
+       .nat = 0,
+       .confcapability = AST_FORMAT_ULAW | AST_FORMAT_ALAW,
+       .capability = 0,
+       .getforward = 0,
+       .needdestroy = 0,
+       .prune = 0,
+       .hookstate = SKINNY_ONHOOK,
+};
+static struct skinny_line_options *default_line = &default_line_struct;
+
+static AST_LIST_HEAD_STATIC(lines, skinny_line);
+
 struct skinny_speeddial {
        ast_mutex_t lock;
        char label[42];
@@ -1216,43 +1288,79 @@ struct skinny_speeddial {
        int laststate;
        int isHint;
 
-       struct skinny_speeddial *next;
+       AST_LIST_ENTRY(skinny_speeddial) list;
        struct skinny_device *parent;
 };
 
 struct skinny_addon {
        ast_mutex_t lock;
        char type[10];
-
-       struct skinny_addon *next;
+       AST_LIST_ENTRY(skinny_addon) list;
        struct skinny_device *parent;
 };
 
-static struct skinny_device {
-       /* A device containing one or more lines */
-       char name[80];
-       char id[16];
-       char version_id[16];
-       char exten[AST_MAX_EXTENSION]; /* Cruddy variable name, pick a better one */
-       int type;
-       int registered;
-       int lastlineinstance;
-       int lastcallreference;
-       int capability;
-       int earlyrtp;
+#define SKINNY_DEVICE_OPTIONS                                  \
+       char name[80];                                          \
+       char id[16];                                            \
+       char version_id[16];                                    \
+       char exten[AST_MAX_EXTENSION];                          \
+       char vmexten[AST_MAX_EXTENSION];                        \
+       int type;                                               \
+       int registered;                                         \
+       int lastlineinstance;                                   \
+       int lastcallreference;                                  \
+       format_t confcapability;                                        \
+       struct ast_codec_pref confprefs;                        \
+       format_t capability;                                            \
+       int earlyrtp;                                           \
+       int transfer;                                           \
+       int callwaiting;                                        \
+       int mwiblink;                                           \
+       int dnd;                                                \
+       int prune;
+
+struct skinny_device {
+       SKINNY_DEVICE_OPTIONS
+       struct type *first;
+       struct type *last;
+       ast_mutex_t lock;
        struct sockaddr_in addr;
        struct in_addr ourip;
-       struct skinny_line *lines;
-       struct skinny_speeddial *speeddials;
-       struct skinny_addon *addons;
-       struct ast_codec_pref prefs;
        struct ast_ha *ha;
        struct skinnysession *session;
-       struct skinny_device *next;
        struct skinny_line *activeline;
-} *devices = NULL;
+       AST_LIST_HEAD(, skinny_line) lines;
+       AST_LIST_HEAD(, skinny_speeddial) speeddials;
+       AST_LIST_HEAD(, skinny_addon) addons;
+       AST_LIST_ENTRY(skinny_device) list;
+};
 
-static struct skinnysession {
+static struct skinny_device_options {
+       SKINNY_DEVICE_OPTIONS
+} default_device_struct = {
+       .transfer = 1,
+       .earlyrtp = 1,
+       .callwaiting = 1,
+       .mwiblink = 0,
+       .dnd = 0,
+       .confcapability = AST_FORMAT_ULAW | AST_FORMAT_ALAW,
+       .capability = 0,
+       .prune = 0,
+};
+static struct skinny_device_options *default_device = &default_device_struct;
+       
+static AST_LIST_HEAD_STATIC(devices, skinny_device);
+
+/*static struct ast_jb_conf default_jbconf =
+{
+       .flags = 0,
+       .max_size = -1,
+       .resync_threshold = -1,
+       .impl = ""
+};
+static struct ast_jb_conf global_jbconf;*/
+
+struct skinnysession {
        pthread_t t;
        ast_mutex_t lock;
        struct sockaddr_in sin;
@@ -1260,10 +1368,12 @@ static struct skinnysession {
        char inbuf[SKINNY_MAX_PACKET];
        char outbuf[SKINNY_MAX_PACKET];
        struct skinny_device *device;
-       struct skinnysession *next;
-} *sessions = NULL;
+       AST_LIST_ENTRY(skinnysession) list;
+};
+
+static struct ast_channel *skinny_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
+static AST_LIST_HEAD_STATIC(sessions, skinnysession);
 
-static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
 static int skinny_devicestate(void *data);
 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
 static int skinny_hangup(struct ast_channel *ast);
@@ -1275,6 +1385,8 @@ static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan
 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s);
+static void mwi_event_cb(const struct ast_event *event, void *userdata);
+static int skinny_reload(void);
 
 static const struct ast_channel_tech skinny_tech = {
        .type = "Skinny",
@@ -1292,7 +1404,7 @@ static const struct ast_channel_tech skinny_tech = {
        .fixup = skinny_fixup,
        .send_digit_begin = skinny_senddigit_begin,
        .send_digit_end = skinny_senddigit_end,
-       .bridge = ast_rtp_bridge,  
+       .bridge = ast_rtp_instance_bridge, 
 };
 
 static int skinny_extensionstate_cb(char *context, char* exten, int state, void *data);
@@ -1301,7 +1413,7 @@ static int skinny_transfer(struct skinny_subchannel *sub);
 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
 {
        struct skinny_device *d = s->device;
-       struct skinny_addon *a = d->addons;
+       struct skinny_addon *a;
        int i;
 
        switch (d->type) {
@@ -1422,7 +1534,8 @@ static void *get_button_template(struct skinnysession *s, struct button_definiti
                        break;
        }
 
-       for (a = d->addons; a; a = a->next) {
+       AST_LIST_LOCK(&d->addons);
+       AST_LIST_TRAVERSE(&d->addons, a, list) {
                if (!strcasecmp(a->type, "7914")) {
                        for (i = 0; i < 14; i++)
                                (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
@@ -1430,6 +1543,7 @@ static void *get_button_template(struct skinnysession *s, struct button_definiti
                        ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
                }
        }
+       AST_LIST_UNLOCK(&d->addons);
 
        return btn;
 }
@@ -1457,7 +1571,7 @@ static struct skinny_line *find_line_by_instance(struct skinny_device *d, int in
        if (!instance)
                instance = 1;
 
-       for (l = d->lines; l; l = l->next) {
+       AST_LIST_TRAVERSE(&d->lines, l, list){
                if (l->instance == instance)
                        break;
        }
@@ -1487,8 +1601,8 @@ static struct skinny_line *find_line_by_name(const char *dest)
        if (!ast_strlen_zero(device))
                checkdevice = 1;
 
-       ast_mutex_lock(&devicelock);
-       for (d = devices; d; d = d->next) {
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE(&devices, d, list){
                if (checkdevice && tmpl)
                        break;
                else if (!checkdevice) {
@@ -1500,19 +1614,19 @@ static struct skinny_line *find_line_by_name(const char *dest)
                        continue;
 
                /* Found the device (or we don't care which device) */
-               for (l = d->lines; l; l = l->next) {
+               AST_LIST_TRAVERSE(&d->lines, l, list){
                        /* Search for the right line */
                        if (!strcasecmp(l->name, line)) {
                                if (tmpl) {
                                        ast_verb(2, "Ambiguous line name: %s\n", line);
-                                       ast_mutex_unlock(&devicelock);
+                                       AST_LIST_UNLOCK(&devices);
                                        return NULL;
                                } else
                                        tmpl = l;
                        }
                }
        }
-       ast_mutex_unlock(&devicelock);
+       AST_LIST_UNLOCK(&devices);
        return tmpl;
 }
 
@@ -1548,9 +1662,9 @@ static struct skinny_subchannel *find_subchannel_by_instance_reference(struct sk
           sub-channel on the list.
            This MIGHT need more love to be right */
        if (!reference)
-               sub = l->sub;
+               sub = AST_LIST_FIRST(&l->sub);
        else {
-               for (sub = l->sub; sub; sub = sub->next) {
+               AST_LIST_TRAVERSE(&l->sub, sub, list) {
                        if (sub->callid == reference)
                                break;
                }
@@ -1567,8 +1681,8 @@ static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_devi
        struct skinny_line *l;
        struct skinny_subchannel *sub = NULL;
 
-       for (l = d->lines; l; l = l->next) {
-               for (sub = l->sub; sub; sub = sub->next) {
+       AST_LIST_TRAVERSE(&d->lines, l, list){
+               AST_LIST_TRAVERSE(&l->sub, sub, list){
                        if (sub->callid == reference)
                                break;
                }
@@ -1590,7 +1704,7 @@ static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device
 {
        struct skinny_speeddial *sd;
 
-       for (sd = d->speeddials; sd; sd = sd->next) {
+       AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
                if (sd->isHint == isHint && sd->instance == instance)
                        break;
        }
@@ -1601,7 +1715,7 @@ static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device
        return sd;
 }
 
-static int codec_skinny2ast(enum skinny_codecs skinnycodec)
+static format_t codec_skinny2ast(enum skinny_codecs skinnycodec)
 {
        switch (skinnycodec) {
        case SKINNY_CODEC_ALAW:
@@ -1623,7 +1737,7 @@ static int codec_skinny2ast(enum skinny_codecs skinnycodec)
        }
 }
 
-static int codec_ast2skinny(int astcodec)
+static int codec_ast2skinny(format_t astcodec)
 {
        switch (astcodec) {
        case AST_FORMAT_ALAW:
@@ -1759,9 +1873,10 @@ static int skinny_register(struct skinny_req *req, struct skinnysession *s)
        struct skinny_speeddial *sd;
        struct sockaddr_in sin;
        socklen_t slen;
+       int instance;
 
-       ast_mutex_lock(&devicelock);
-       for (d = devices; d; d = d->next) {
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE(&devices, d, list){
                if (!strcasecmp(req->data.reg.name, d->id)
                                && ast_apply_ha(d->ha, &(s->sin))) {
                        s->device = d;
@@ -1779,17 +1894,42 @@ static int skinny_register(struct skinny_req *req, struct skinnysession *s)
                        }
                        d->ourip = sin.sin_addr;
 
-                       for (sd = d->speeddials; sd; sd = sd->next) {
+                       AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
                                sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd);
                        }
-                       for (l = d->lines; l; l = l->next) {
-                               register_exten(l);
-                               ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
+                       instance = 0;
+                       AST_LIST_TRAVERSE(&d->lines, l, list) {
+                               instance++;
+                       }
+                       AST_LIST_TRAVERSE(&d->lines, l, list) {
+                               /* FIXME: All sorts of issues will occur if this line is already connected to a device */
+                               if (l->device) {
+                                       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Rejected\r\nCause: LINE_ALREADY_CONNECTED\r\n", l->name, l->device->name); 
+                                       ast_verb(1, "Line %s already connected to %s. Not connecting to %s.\n", l->name, l->device->name, d->name);
+                               } else {
+                                       l->device = d;
+                                       l->capability = l->confcapability & d->capability;
+                                       l->prefs = l->confprefs;
+                                       if (!l->prefs.order[0]) {
+                                               l->prefs = d->confprefs;
+                                       }
+                                       /* l->capability = d->capability;
+                                       l->prefs = d->prefs; */
+                                       l->instance = instance;
+                                       l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
+                                       set_callforwards(l, NULL, 0);
+                                       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Registered\r\n", l->name, d->name);
+                                       register_exten(l);
+                                       /* initialize MWI on line and device */
+                                       mwi_event_cb(0, l);
+                                       ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
+                               }
+                               --instance;
                        }
                        break;
                }
        }
-       ast_mutex_unlock(&devicelock);
+       AST_LIST_UNLOCK(&devices);
        if (!d) {
                return 0;
        }
@@ -1808,21 +1948,160 @@ static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
                d->session = NULL;
                d->registered = 0;
 
-               for (sd = d->speeddials; sd; sd = sd->next) {
+               AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
                        if (sd->stateid > -1)
                                ast_extension_state_del(sd->stateid, NULL);
                }
-               for (l = d->lines; l; l = l->next) {
-                       unregister_exten(l);
-                       ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
+               AST_LIST_TRAVERSE(&d->lines, l, list) {
+                       if (l->device == d) {
+                               l->device = NULL;
+                               l->capability = 0;
+                               ast_parse_allow_disallow(&l->prefs, &l->capability, "all", 0);                  
+                               l->instance = 0;
+                               manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Unregistered\r\n", l->name, d->name);
+                               unregister_exten(l);
+                               ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "Skinny/%s@%s", l->name, d->name);
+                       }
                }
        }
 
        return -1; /* main loop will destroy the session */
 }
 
-static int transmit_response(struct skinnysession *s, struct skinny_req *req)
+#ifdef SKINNY_DEVMODE
+static char *message2str(int type)
+{
+       char *tmp;
+
+       switch (type) {
+       case KEEP_ALIVE_MESSAGE:
+               return "KEEP_ALIVE_MESSAGE";
+       case REGISTER_MESSAGE:
+               return "REGISTER_MESSAGE";
+       case IP_PORT_MESSAGE:
+               return "IP_PORT_MESSAGE";
+       case KEYPAD_BUTTON_MESSAGE:
+               return "KEYPAD_BUTTON_MESSAGE";
+       case ENBLOC_CALL_MESSAGE:
+               return "ENBLOC_CALL_MESSAGE";
+       case STIMULUS_MESSAGE:
+               return "STIMULUS_MESSAGE";
+       case OFFHOOK_MESSAGE:
+               return "OFFHOOK_MESSAGE";
+       case ONHOOK_MESSAGE:
+               return "ONHOOK_MESSAGE";
+       case CAPABILITIES_RES_MESSAGE:
+               return "CAPABILITIES_RES_MESSAGE";
+       case SPEED_DIAL_STAT_REQ_MESSAGE:
+               return "SPEED_DIAL_STAT_REQ_MESSAGE";
+       case LINE_STATE_REQ_MESSAGE:
+               return "LINE_STATE_REQ_MESSAGE";
+       case TIME_DATE_REQ_MESSAGE:
+               return "TIME_DATE_REQ_MESSAGE";
+       case BUTTON_TEMPLATE_REQ_MESSAGE:
+               return "BUTTON_TEMPLATE_REQ_MESSAGE";
+       case VERSION_REQ_MESSAGE:
+               return "VERSION_REQ_MESSAGE";
+       case SERVER_REQUEST_MESSAGE:
+               return "SERVER_REQUEST_MESSAGE";
+       case ALARM_MESSAGE:
+               return "ALARM_MESSAGE";
+       case OPEN_RECEIVE_CHANNEL_ACK_MESSAGE:
+               return "OPEN_RECEIVE_CHANNEL_ACK_MESSAGE";
+       case SOFT_KEY_SET_REQ_MESSAGE:
+               return "SOFT_KEY_SET_REQ_MESSAGE";
+       case SOFT_KEY_EVENT_MESSAGE:
+               return "SOFT_KEY_EVENT_MESSAGE";
+       case UNREGISTER_MESSAGE:
+               return "UNREGISTER_MESSAGE";
+       case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
+               return "SOFT_KEY_TEMPLATE_REQ_MESSAGE";
+       case HEADSET_STATUS_MESSAGE:
+               return "HEADSET_STATUS_MESSAGE";
+       case REGISTER_AVAILABLE_LINES_MESSAGE:
+               return "REGISTER_AVAILABLE_LINES_MESSAGE";
+       case REGISTER_ACK_MESSAGE:
+               return "REGISTER_ACK_MESSAGE";
+       case START_TONE_MESSAGE:
+               return "START_TONE_MESSAGE";
+       case STOP_TONE_MESSAGE:
+               return "STOP_TONE_MESSAGE";
+       case SET_RINGER_MESSAGE:
+               return "SET_RINGER_MESSAGE";
+       case SET_LAMP_MESSAGE:
+               return "SET_LAMP_MESSAGE";
+       case SET_SPEAKER_MESSAGE:
+               return "SET_SPEAKER_MESSAGE";
+       case SET_MICROPHONE_MESSAGE:
+               return "SET_MICROPHONE_MESSAGE";
+       case START_MEDIA_TRANSMISSION_MESSAGE:
+               return "START_MEDIA_TRANSMISSION_MESSAGE";
+       case STOP_MEDIA_TRANSMISSION_MESSAGE:
+               return "STOP_MEDIA_TRANSMISSION_MESSAGE";
+       case CALL_INFO_MESSAGE:
+               return "CALL_INFO_MESSAGE";
+       case FORWARD_STAT_MESSAGE:
+               return "FORWARD_STAT_MESSAGE";
+       case SPEED_DIAL_STAT_RES_MESSAGE:
+               return "SPEED_DIAL_STAT_RES_MESSAGE";
+       case LINE_STAT_RES_MESSAGE:
+               return "LINE_STAT_RES_MESSAGE";
+       case DEFINETIMEDATE_MESSAGE:
+               return "DEFINETIMEDATE_MESSAGE";
+       case BUTTON_TEMPLATE_RES_MESSAGE:
+               return "BUTTON_TEMPLATE_RES_MESSAGE";
+       case VERSION_RES_MESSAGE:
+               return "VERSION_RES_MESSAGE";
+       case DISPLAYTEXT_MESSAGE:
+               return "DISPLAYTEXT_MESSAGE";
+       case CLEAR_NOTIFY_MESSAGE:
+               return "CLEAR_NOTIFY_MESSAGE";
+       case CLEAR_DISPLAY_MESSAGE:
+               return "CLEAR_DISPLAY_MESSAGE";
+       case CAPABILITIES_REQ_MESSAGE:
+               return "CAPABILITIES_REQ_MESSAGE";
+       case REGISTER_REJ_MESSAGE:
+               return "REGISTER_REJ_MESSAGE";
+       case SERVER_RES_MESSAGE:
+               return "SERVER_RES_MESSAGE";
+       case RESET_MESSAGE:
+               return "RESET_MESSAGE";
+       case KEEP_ALIVE_ACK_MESSAGE:
+               return "KEEP_ALIVE_ACK_MESSAGE";
+       case OPEN_RECEIVE_CHANNEL_MESSAGE:
+               return "OPEN_RECEIVE_CHANNEL_MESSAGE";
+       case CLOSE_RECEIVE_CHANNEL_MESSAGE:
+               return "CLOSE_RECEIVE_CHANNEL_MESSAGE";
+       case SOFT_KEY_TEMPLATE_RES_MESSAGE:
+               return "SOFT_KEY_TEMPLATE_RES_MESSAGE";
+       case SOFT_KEY_SET_RES_MESSAGE:
+               return "SOFT_KEY_SET_RES_MESSAGE";
+       case SELECT_SOFT_KEYS_MESSAGE:
+               return "SELECT_SOFT_KEYS_MESSAGE";
+       case CALL_STATE_MESSAGE:
+               return "CALL_STATE_MESSAGE";
+       case DISPLAY_PROMPT_STATUS_MESSAGE:
+               return "DISPLAY_PROMPT_STATUS_MESSAGE";
+       case CLEAR_PROMPT_MESSAGE:
+               return "CLEAR_PROMPT_MESSAGE";
+       case DISPLAY_NOTIFY_MESSAGE:
+               return "DISPLAY_NOTIFY_MESSAGE";
+       case ACTIVATE_CALL_PLANE_MESSAGE:
+               return "ACTIVATE_CALL_PLANE_MESSAGE";
+       case DIALED_NUMBER_MESSAGE:
+               return "DIALED_NUMBER_MESSAGE";
+       default:
+               if (!(tmp = ast_threadstorage_get(&message2str_threadbuf, MESSAGE2STR_BUFSIZE)))
+                       return "Unknown";
+               snprintf(tmp, MESSAGE2STR_BUFSIZE, "UNKNOWN_MESSAGE-%d", type);
+               return tmp;
+       }
+}
+#endif
+
+static int transmit_response(struct skinny_device *d, struct skinny_req *req)
 {
+       struct skinnysession *s = d->session;
        int res = 0;
 
        if (!s) {
@@ -1832,20 +2111,20 @@ static int transmit_response(struct skinnysession *s, struct skinny_req *req)
 
        ast_mutex_lock(&s->lock);
 
-       if (skinnydebug)
-               ast_log(LOG_VERBOSE, "writing packet type %04X (%d bytes) to socket %d\n", letohl(req->e), letohl(req->len)+8, s->fd);
+       SKINNY_DEVONLY(if (skinnydebug>1) ast_verb(4, "Transmitting %s to %s\n", message2str(req->e), d->name);)
 
        if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
                ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
+               ast_mutex_unlock(&s->lock);
                return -1;
        }
 
-       memset(s->outbuf,0,sizeof(s->outbuf));
+       memset(s->outbuf, 0, sizeof(s->outbuf));
        memcpy(s->outbuf, req, skinny_header_size);
        memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
 
        res = write(s->fd, s->outbuf, letohl(req->len)+8);
-
+       
        if (res != letohl(req->len)+8) {
                ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
                if (res == -1) {
@@ -1856,11 +2135,12 @@ static int transmit_response(struct skinnysession *s, struct skinny_req *req)
                
        }
        
+       ast_free(req);
        ast_mutex_unlock(&s->lock);
        return 1;
 }
 
-static void transmit_speaker_mode(struct skinnysession *s, int mode)
+static void transmit_speaker_mode(struct skinny_device *d, int mode)
 {
        struct skinny_req *req;
 
@@ -1868,10 +2148,10 @@ static void transmit_speaker_mode(struct skinnysession *s, int mode)
                return;
 
        req->data.setspeaker.mode = htolel(mode);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 /*
-static void transmit_microphone_mode(struct skinnysession *s, int mode)
+static void transmit_microphone_mode(struct skinny_device *d, int mode)
 {
        struct skinny_req *req;
 
@@ -1879,19 +2159,23 @@ static void transmit_microphone_mode(struct skinnysession *s, int mode)
                return;
 
        req->data.setmicrophone.mode = htolel(mode);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 */
 
-static void transmit_callinfo(struct skinnysession *s, const char *fromname, const char *fromnum, const char *toname, const char *tonum, int instance, int callid, int calltype)
+static void transmit_callinfo(struct skinny_device *d, const char *fromname, const char *fromnum, const char *toname, const char *tonum, int instance, int callid, int calltype)
 {
        struct skinny_req *req;
 
+       /* We should not be able to get here without a device */
+       if (!d)
+               return;
+
        if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
                return;
 
        if (skinnydebug)
-                       ast_verb(1, "Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, s->device->name, instance);
+                       ast_verb(1, "Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, d->name, instance);
 
        if (fromname) {
                ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
@@ -1908,10 +2192,10 @@ static void transmit_callinfo(struct skinnysession *s, const char *fromname, con
        req->data.callinfo.instance = htolel(instance);
        req->data.callinfo.reference = htolel(callid);
        req->data.callinfo.type = htolel(calltype);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_connect(struct skinnysession *s, struct skinny_subchannel *sub)
+static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
 {
        struct skinny_req *req;
        struct skinny_line *l = sub->parent;
@@ -1928,10 +2212,10 @@ static void transmit_connect(struct skinnysession *s, struct skinny_subchannel *
        req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
        req->data.openreceivechannel.echo = htolel(0);
        req->data.openreceivechannel.bitrate = htolel(0);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_tone(struct skinnysession *s, int tone, int instance, int reference)
+static void transmit_tone(struct skinny_device *d, int tone, int instance, int reference)
 {
        struct skinny_req *req;
 
@@ -1953,13 +2237,15 @@ static void transmit_tone(struct skinnysession *s, int tone, int instance, int r
                req->data.stoptone.reference = htolel(reference);
        }
 
-       if (tone > 0) {
-               req->data.starttone.tone = htolel(tone);
-       }
-       transmit_response(s, req);
+       //Bad, tone is already set so this is redundant and a change to the if above
+       //may lead to issues where we try to set a tone to a stop_tone_message
+       //if (tone > 0) {
+       //      req->data.starttone.tone = htolel(tone);
+       //}
+       transmit_response(d, req);
 }
 
-static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
+static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
 {
        struct skinny_req *req;
 
@@ -1970,10 +2256,10 @@ static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int c
        req->data.selectsoftkey.reference = htolel(callid);
        req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
        req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_lamp_indication(struct skinnysession *s, int stimulus, int instance, int indication)
+static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
 {
        struct skinny_req *req;
 
@@ -1983,10 +2269,10 @@ static void transmit_lamp_indication(struct skinnysession *s, int stimulus, int
        req->data.setlamp.stimulus = htolel(stimulus);
        req->data.setlamp.stimulusInstance = htolel(instance);
        req->data.setlamp.deviceStimulus = htolel(indication);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_ringer_mode(struct skinnysession *s, int mode)
+static void transmit_ringer_mode(struct skinny_device *d, int mode)
 {
        struct skinny_req *req;
 
@@ -2008,10 +2294,10 @@ static void transmit_ringer_mode(struct skinnysession *s, int mode)
        /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
           Perhaps a packet capture can shed some light on this. */
        req->data.setringer.unknown2 = htolel(1);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_displaymessage(struct skinnysession *s, const char *text, int instance, int reference)
+static void transmit_displaymessage(struct skinny_device *d, const char *text, int instance, int reference)
 {
        struct skinny_req *req;
 
@@ -2019,8 +2305,13 @@ static void transmit_displaymessage(struct skinnysession *s, const char *text, i
                if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
                        return;
 
-               req->data.clearpromptstatus.lineInstance = instance;
-               req->data.clearpromptstatus.callReference = reference;
+               //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
+               //if we are clearing the display, it appears there is no instance and refernece info (size 0)
+               //req->data.clearpromptstatus.lineInstance = instance;
+               //req->data.clearpromptstatus.callReference = reference;
+
+               /* send datetime message. We have to do it here because it will clear the display on the phone if we do it elsewhere */
+               handle_time_date_req_message(NULL, d->session);
 
                if (skinnydebug)
                        ast_verb(1, "Clearing Display\n");
@@ -2033,10 +2324,10 @@ static void transmit_displaymessage(struct skinnysession *s, const char *text, i
                        ast_verb(1, "Displaying message '%s'\n", req->data.displaytext.text);
        }
 
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_displaynotify(struct skinnysession *s, const char *text, int t)
+static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
 {
        struct skinny_req *req;
 
@@ -2049,10 +2340,10 @@ static void transmit_displaynotify(struct skinnysession *s, const char *text, in
        if (skinnydebug)
                ast_verb(1, "Displaying notify '%s'\n", text);
 
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_displaypromptstatus(struct skinnysession *s, const char *text, int t, int instance, int callid)
+static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
 {
        struct skinny_req *req;
 
@@ -2078,10 +2369,10 @@ static void transmit_displaypromptstatus(struct skinnysession *s, const char *te
                        ast_verb(1, "Displaying Prompt Status '%s'\n", text);
        }
 
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_dialednumber(struct skinnysession *s, const char *text, int instance, int callid)
+static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
 {
        struct skinny_req *req;
 
@@ -2092,10 +2383,10 @@ static void transmit_dialednumber(struct skinnysession *s, const char *text, int
        req->data.dialednumber.lineInstance = htolel(instance);
        req->data.dialednumber.callReference = htolel(callid);
 
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_closereceivechannel(struct skinnysession *s, struct skinny_subchannel *sub)
+static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
 {
        struct skinny_req *req;
 
@@ -2104,10 +2395,10 @@ static void transmit_closereceivechannel(struct skinnysession *s, struct skinny_
 
        req->data.closereceivechannel.conferenceId = htolel(0);
        req->data.closereceivechannel.partyId = htolel(sub->callid);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_stopmediatransmission(struct skinnysession *s, struct skinny_subchannel *sub)
+static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
 {
        struct skinny_req *req;
 
@@ -2116,10 +2407,10 @@ static void transmit_stopmediatransmission(struct skinnysession *s, struct skinn
 
        req->data.stopmedia.conferenceId = htolel(0);
        req->data.stopmedia.passThruPartyId = htolel(sub->callid);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_activatecallplane(struct skinnysession *s, struct skinny_line *l)
+static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
 {
        struct skinny_req *req;
 
@@ -2127,10 +2418,10 @@ static void transmit_activatecallplane(struct skinnysession *s, struct skinny_li
                return;
 
        req->data.activatecallplane.lineInstance = htolel(l->instance);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_callstateonly(struct skinnysession *s, struct skinny_subchannel *sub, int state)
+static void transmit_callstateonly(struct skinny_device *d, struct skinny_subchannel *sub, int state)
 {
        struct skinny_req *req;
 
@@ -2140,10 +2431,10 @@ static void transmit_callstateonly(struct skinnysession *s, struct skinny_subcha
        req->data.callstate.callState = htolel(state);
        req->data.callstate.lineInstance = htolel(sub->parent->instance);
        req->data.callstate.callReference = htolel(sub->callid);
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
-static void transmit_callstate(struct skinnysession *s, int instance, int state, unsigned callid)
+static void transmit_callstate(struct skinny_device *d, int instance, int state, unsigned callid)
 {
        struct skinny_req *req;
 
@@ -2153,18 +2444,18 @@ static void transmit_callstate(struct skinnysession *s, int instance, int state,
 
                req->data.closereceivechannel.conferenceId = htolel(callid);
                req->data.closereceivechannel.partyId = htolel(callid);
-               transmit_response(s, req);
+               transmit_response(d, req);
 
                if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
                        return;
 
                req->data.stopmedia.conferenceId = htolel(callid);
                req->data.stopmedia.passThruPartyId = htolel(callid);
-               transmit_response(s, req);
+               transmit_response(d, req);
 
-               transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
+               transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
 
-               transmit_displaypromptstatus(s, NULL, 0, instance, callid);
+               transmit_displaypromptstatus(d, NULL, 0, instance, callid);
        }
 
        if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
@@ -2173,10 +2464,10 @@ static void transmit_callstate(struct skinnysession *s, int instance, int state,
        req->data.callstate.callState = htolel(state);
        req->data.callstate.lineInstance = htolel(instance);
        req->data.callstate.callReference = htolel(callid);
-       transmit_response(s, req);
+       transmit_response(d, req);
 
        if (state == SKINNY_ONHOOK) {
-               transmit_selectsoftkeys(s, 0, 0, KEYDEF_ONHOOK);
+               transmit_selectsoftkeys(d, 0, 0, KEYDEF_ONHOOK);
        }
 
        if (state == SKINNY_OFFHOOK || state == SKINNY_ONHOOK) {
@@ -2184,12 +2475,12 @@ static void transmit_callstate(struct skinnysession *s, int instance, int state,
                        return;
 
                req->data.activatecallplane.lineInstance = htolel(instance);
-               transmit_response(s, req);
+               transmit_response(d, req);
        }
 }
 
 
-static void transmit_cfwdstate(struct skinnysession *s, struct skinny_line *l)
+static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
 {
        struct skinny_req *req;
        int anyon = 0;
@@ -2230,14 +2521,13 @@ static void transmit_cfwdstate(struct skinnysession *s, struct skinny_line *l)
        else
                req->data.forwardstat.activeforward = htolel(0);
 
-       transmit_response(s, req);
+       transmit_response(d, req);
 }
 
 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
 {
        struct skinny_speeddial *sd = data;
        struct skinny_device *d = sd->parent;
-       struct skinnysession *s = d->session;
        char hint[AST_MAX_EXTENSION];
        int callstate = SKINNY_CALLREMOTEMULTILINE;
        int lamp = SKINNY_LAMP_OFF;
@@ -2279,119 +2569,133 @@ static int skinny_extensionstate_cb(char *context, char *exten, int state, void
                }
        }
 
-       transmit_lamp_indication(s, STIMULUS_LINE, sd->instance, lamp);
-       transmit_callstate(s, sd->instance, callstate, 0);
+       transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, lamp);
+       transmit_callstate(d, sd->instance, callstate, 0);
        sd->laststate = state;
 
        return 0;
 }
 
-static void mwi_event_cb(const struct ast_event *event, void *userdata)
+static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
 {
-       /* This module does not handle MWI in an event-based manner.  However, it
-        * subscribes to MWI for each mailbox that is configured so that the core
-        * knows that we care about it.  Then, chan_skinny will get the MWI from the
-        * event cache instead of checking the mailbox directly. */
-}
+       struct ast_channel *c = sub->owner;
+       struct skinny_line *l = sub->parent;
+       struct skinny_device *d = l->device;
 
-static int has_voicemail(struct skinny_line *l)
-{
-       int new_msgs;
-       struct ast_event *event;
-       char *mailbox, *context;
-
-       context = mailbox = ast_strdupa(l->mailbox);
-       strsep(&context, "@");
-       if (ast_strlen_zero(context))
-               context = "default";
-
-       event = ast_event_get_cached(AST_EVENT_MWI,
-               AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
-               AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
-               AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
-               AST_EVENT_IE_END);
-
-       if (event) {
-               new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
-               ast_event_destroy(event);
-       } else
-               new_msgs = ast_app_has_voicemail(l->mailbox, NULL);
-
-       return new_msgs;
+       if (ast_strlen_zero(c->cid.cid_num) || ast_strlen_zero(c->connected.id.number))
+               return;
+
+       if (sub->owner->_state == AST_STATE_UP) {
+               transmit_callstate(d, l->instance, SKINNY_CONNECTED, sub->callid);
+               transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
+               if (sub->outgoing)
+                       transmit_callinfo(d, c->connected.id.name, c->connected.id.number, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
+               else
+                       transmit_callinfo(d, l->cid_name, l->cid_num, c->connected.id.name, c->connected.id.number, l->instance, sub->callid, 2);
+       } else {
+               if (sub->outgoing) {
+                       transmit_callstate(d, l->instance, SKINNY_RINGIN, sub->callid);
+                       transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
+                       transmit_callinfo(d, c->connected.id.name, c->connected.id.number, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
+               } else {
+                       if (!sub->ringing) {
+                               transmit_callstate(d, l->instance, SKINNY_RINGOUT, sub->callid);
+                               transmit_displaypromptstatus(d, "Ring-Out", 0, l->instance, sub->callid);
+                               sub->ringing = 1;
+                       } else {
+                               transmit_callstate(d, l->instance, SKINNY_PROGRESS, sub->callid);
+                               transmit_displaypromptstatus(d, "Call Progress", 0, l->instance, sub->callid);
+                               sub->progress = 1;
+                       }
+
+                       transmit_callinfo(d, l->cid_name, l->cid_num, c->connected.id.name, c->connected.id.number, l->instance, sub->callid, 2);
+               }
+       }
 }
 
-static void do_housekeeping(struct skinnysession *s)
+static void mwi_event_cb(const struct ast_event *event, void *userdata)
 {
-       int device_lamp = 0;
-       struct skinny_device *d = s->device;
-       struct skinny_line *l;
+       struct skinny_line *l = userdata;
+       struct skinny_device *d = l->device;
+       if (d) {
+               struct skinnysession *s = d->session;
+               struct skinny_line *l2;
+               int new_msgs = 0;
+               int dev_msgs = 0;
+
+               if (s) {
+                       if (event) {
+                               l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
+                       }
 
-       /* Update time on device */
-       handle_time_date_req_message(NULL, s);
+                       if (l->newmsgs) {
+                               transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
+                       } else {
+                               transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
+                       }
 
-       /* Set MWI on individual lines */
-       for (l = d->lines; l; l = l->next) {
-               if (has_voicemail(l)) {
-                       if (skinnydebug)
-                               ast_verb(1, "Checking for voicemail Skinny %s@%s\n", l->name, d->name);
-                       if (skinnydebug)
-                               ast_verb(1, "Skinny %s@%s has voicemail!\n", l->name, d->name);
-                       transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
-                       device_lamp++;
-               } else {
-                       transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
+                       /* find out wether the device lamp should be on or off */
+                       AST_LIST_TRAVERSE(&d->lines, l2, list) {
+                               if (l2->newmsgs) {
+                                       dev_msgs++;
+                               }
+                       }
+
+                       if (dev_msgs) {
+                               transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
+                       } else {
+                               transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
+                       }
+                       ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", new_msgs);
                }
        }
-       /* If at least one line has VM, turn the device level lamp on */
-       if (device_lamp)
-               transmit_lamp_indication(s, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_ON);
-       else
-               transmit_lamp_indication(s, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
 }
 
 /* I do not believe skinny can deal with video.
    Anyone know differently? */
 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
-static enum ast_rtp_get_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
+static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
 {
        struct skinny_subchannel *sub = NULL;
 
        if (!(sub = c->tech_pvt) || !(sub->vrtp))
-               return AST_RTP_GET_FAILED;
+               return AST_RTP_GLUE_RESULT_FORBID;
 
-       *rtp = sub->vrtp;
+       ao2_ref(sub->vrtp, +1);
+       *instance = sub->vrtp;
 
-       return AST_RTP_TRY_NATIVE;
+       return AST_RTP_GLUE_RESULT_REMOTE;
 }
 
-static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
+static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
 {
        struct skinny_subchannel *sub = NULL;
        struct skinny_line *l;
-       enum ast_rtp_get_result res = AST_RTP_TRY_NATIVE;
+       enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;
 
        if (skinnydebug)
                ast_verb(1, "skinny_get_rtp_peer() Channel = %s\n", c->name);
 
 
        if (!(sub = c->tech_pvt))
-               return AST_RTP_GET_FAILED;
+               return AST_RTP_GLUE_RESULT_FORBID;
 
        ast_mutex_lock(&sub->lock);
 
        if (!(sub->rtp)){
                ast_mutex_unlock(&sub->lock);
-               return AST_RTP_GET_FAILED;
+               return AST_RTP_GLUE_RESULT_FORBID;
        }
-       
-       *rtp = sub->rtp;
+
+       ao2_ref(sub->rtp, +1);
+       *instance = sub->rtp;
 
        l = sub->parent;
 
-       if (!l->canreinvite || l->nat){
-               res = AST_RTP_TRY_PARTIAL;
+       if (!l->directmedia || l->nat){
+               res = AST_RTP_GLUE_RESULT_LOCAL;
                if (skinnydebug)
-                       ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_TRY_PARTIAL \n");
+                       ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
        }
 
        ast_mutex_unlock(&sub->lock);
@@ -2400,15 +2704,15 @@ static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct
 
 }
 
-static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
+static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, format_t codecs, int nat_active)
 {
        struct skinny_subchannel *sub;
        struct skinny_line *l;
        struct skinny_device *d;
        struct skinnysession *s;
        struct ast_format_list fmt;
-       struct sockaddr_in us;
-       struct sockaddr_in them;
+       struct sockaddr_in us = { 0, };
+       struct sockaddr_in them = { 0, };
        struct skinny_req *req;
        
        sub = c->tech_pvt;
@@ -2421,11 +2725,11 @@ static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struc
        }
 
        l = sub->parent;
-       d = l->parent;
+       d = l->device;
        s = d->session;
 
        if (rtp){
-               ast_rtp_get_peer(rtp, &them);
+               ast_rtp_instance_get_remote_address(rtp, &them);
 
                /* Shutdown any early-media or previous media on re-invite */
                if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
@@ -2433,7 +2737,7 @@ static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struc
 
                req->data.stopmedia.conferenceId = htolel(sub->callid);
                req->data.stopmedia.passThruPartyId = htolel(sub->callid);
-               transmit_response(s, req);
+               transmit_response(d, req);
 
                if (skinnydebug)
                        ast_verb(1, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
@@ -2444,12 +2748,12 @@ static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struc
                fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
 
                if (skinnydebug)
-                       ast_verb(1, "Setting payloadType to '%d' (%d ms)\n", fmt.bits, fmt.cur_ms);
+                       ast_verb(1, "Setting payloadType to '%s' (%d ms)\n", ast_getformatname(fmt.bits), fmt.cur_ms);
 
                req->data.startmedia.conferenceId = htolel(sub->callid);
                req->data.startmedia.passThruPartyId = htolel(sub->callid);
-               if (!(l->canreinvite) || (l->nat)){
-                       ast_rtp_get_us(rtp, &us);
+               if (!(l->directmedia) || (l->nat)){
+                       ast_rtp_instance_get_local_address(rtp, &us);
                        req->data.startmedia.remoteIp = htolel(d->ourip.s_addr);
                        req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
                } else {
@@ -2462,7 +2766,7 @@ static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struc
                req->data.startmedia.qualifier.vad = htolel(0);
                req->data.startmedia.qualifier.packets = htolel(0);
                req->data.startmedia.qualifier.bitRate = htolel(0);
-               transmit_response(s, req);
+               transmit_response(d, req);
 
                return 0;
        }
@@ -2470,50 +2774,63 @@ static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struc
        return 0;
 }
 
-static struct ast_rtp_protocol skinny_rtp = {
+static struct ast_rtp_glue skinny_rtp_glue = {
        .type = "Skinny",
        .get_rtp_info = skinny_get_rtp_peer,
        .get_vrtp_info = skinny_get_vrtp_peer,
-       .set_rtp_peer = skinny_set_rtp_peer,
+       .update_peer = skinny_set_rtp_peer,
 };
 
-static char *handle_skinny_set_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        switch (cmd) {
        case CLI_INIT:
-               e->command = "skinny set debug [off]";
+#ifdef SKINNY_DEVMODE
+               e->command = "skinny set debug {off|on|packet}";
                e->usage =
-                       "Usage: skinny set debug [off]\n"
+                       "Usage: skinny set debug {off|on|packet}\n"
                        "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
+#else
+               e->command = "skinny set debug {off|on}";
+               e->usage =
+                       "Usage: skinny set debug {off|on}\n"
+                       "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
+#endif
                return NULL;
        case CLI_GENERATE:
                return NULL;
        }
        
-       if (a->argc < 3 || a->argc > 4)
+       if (a->argc != e->args)
                return CLI_SHOWUSAGE;
 
-       if (a->argc == 3) {
+       if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
                skinnydebug = 1;
                ast_cli(a->fd, "Skinny Debugging Enabled\n");
                return CLI_SUCCESS;
-       } else if (!strncasecmp(a->argv[3], "off", 3)) {
+       } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
                skinnydebug = 0;
                ast_cli(a->fd, "Skinny Debugging Disabled\n");
                return CLI_SUCCESS;
+#ifdef SKINNY_DEVMODE
+       } else if (!strncasecmp(a->argv[e->args - 1], "packet", 6)) {
+               skinnydebug = 2;
+               ast_cli(a->fd, "Skinny Debugging Enabled including Packets\n");
+               return CLI_SUCCESS;
+#endif
        } else {
                return CLI_SHOWUSAGE;
        }
 }
 
-static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static char *handle_skinny_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        switch (cmd) {
        case CLI_INIT:
-               e->command = "skinny set debug {on|off}";
+               e->command = "skinny reload";
                e->usage =
-                       "Usage: skinny set debug {on|off}\n"
-                       "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
+                       "Usage: skinny reload\n"
+                       "       Reloads the chan_skinny configuration\n";
                return NULL;
        case CLI_GENERATE:
                return NULL;
@@ -2522,17 +2839,9 @@ static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct as
        if (a->argc != e->args)
                return CLI_SHOWUSAGE;
 
-       if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
-               skinnydebug = 1;
-               ast_cli(a->fd, "Skinny Debugging Enabled\n");
-               return CLI_SUCCESS;
-       } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
-               skinnydebug = 0;
-               ast_cli(a->fd, "Skinny Debugging Disabled\n");
-               return CLI_SUCCESS;
-       } else {
-               return CLI_SHOWUSAGE;
-       }
+       skinny_reload();
+       return CLI_SUCCESS;
+
 }
 
 static char *complete_skinny_devices(const char *word, int state)
@@ -2541,7 +2850,7 @@ static char *complete_skinny_devices(const char *word, int state)
        char *result = NULL;
        int wordlen = strlen(word), which = 0;
 
-       for (d = devices; d && !result; d = d->next) {
+       AST_LIST_TRAVERSE(&devices, d, list) {
                if (!strncasecmp(word, d->id, wordlen) && ++which > state)
                        result = ast_strdup(d->id);
        }
@@ -2569,8 +2878,8 @@ static char *complete_skinny_show_line(const char *line, const char *word, int p
        if (pos != 3)
                return NULL;
        
-       for (d = devices; d && !result; d = d->next) {
-               for (l = d->lines; l && !result; l = l->next) {
+       AST_LIST_TRAVERSE(&devices, d, list) {
+               AST_LIST_TRAVERSE(&d->lines, l, list) {
                        if (!strncasecmp(word, l->name, wordlen) && ++which > state)
                                result = ast_strdup(l->name);
                }
@@ -2598,9 +2907,8 @@ static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cl
        if (a->argc < 3 || a->argc > 4)
                return CLI_SHOWUSAGE;
 
-       ast_mutex_lock(&devicelock);
-
-       for (d = devices; d; d = d->next) {
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE(&devices, d, list) {
                int fullrestart = 0;
                if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
                        if (!(d->session))
@@ -2618,10 +2926,10 @@ static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cl
                                req->data.reset.resetType = 1;
 
                        ast_verb(3, "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
-                       transmit_response(d->session, req);
+                       transmit_response(d, req);
                }
        }
-       ast_mutex_unlock(&devicelock);
+       AST_LIST_UNLOCK(&devices);
        return CLI_SUCCESS;
 }
 
@@ -2732,10 +3040,102 @@ static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
                ast_cli(fd, "none");
 }
 
-static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static char *_skinny_show_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
 {
        struct skinny_device *d;
        struct skinny_line *l;
+       const char *id;
+       char idtext[256] = "";
+       int total_devices = 0;
+
+       if (s) {        /* Manager - get ActionID */
+               id = astman_get_header(m, "ActionID");
+               if (!ast_strlen_zero(id))
+                       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
+       }
+
+       switch (argc) {
+       case 3:
+               break;
+       default:
+               return CLI_SHOWUSAGE;
+       }
+
+       if (!s) {
+               ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
+               ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
+       }
+
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE(&devices, d, list) {
+               int numlines = 0;
+               total_devices++;
+               AST_LIST_TRAVERSE(&d->lines, l, list) {
+                       numlines++;
+               }
+               if (!s) {
+                       ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
+                               d->name,
+                               d->id,
+                               d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
+                               device2str(d->type),
+                               d->registered?'Y':'N',
+                               numlines);
+               } else {
+                       astman_append(s,
+                               "Event: DeviceEntry\r\n%s"
+                               "Channeltype: SKINNY\r\n"
+                               "ObjectName: %s\r\n"
+                               "ChannelObjectType: device\r\n"
+                               "DeviceId: %s\r\n"
+                               "IPaddress: %s\r\n"
+                               "Type: %s\r\n"
+                               "Devicestatus: %s\r\n"
+                               "NumberOfLines: %d\r\n",
+                               idtext,
+                               d->name,
+                               d->id,
+                               d->session?ast_inet_ntoa(d->session->sin.sin_addr):"-none-",
+                               device2str(d->type),
+                               d->registered?"registered":"unregistered",
+                               numlines);
+               }
+       }
+       AST_LIST_UNLOCK(&devices);
+
+       if (total)
+               *total = total_devices;
+       
+       return CLI_SUCCESS;
+}
+
+/*! \brief  Show SKINNY devices in the manager API */
+/*    Inspired from chan_sip */
+static int manager_skinny_show_devices(struct mansession *s, const struct message *m)
+{
+       const char *id = astman_get_header(m, "ActionID");
+       const char *a[] = {"skinny", "show", "devices"};
+       char idtext[256] = "";
+       int total = 0;
+
+       if (!ast_strlen_zero(id))
+               snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
+
+       astman_send_listack(s, m, "Device status list will follow", "start");
+       /* List the devices in separate manager events */
+       _skinny_show_devices(-1, &total, s, m, 3, a);
+       /* Send final confirmation */
+       astman_append(s,
+       "Event: DevicelistComplete\r\n"
+       "EventList: Complete\r\n"
+       "ListItems: %d\r\n"
+       "%s"
+       "\r\n", total, idtext);
+       return 0;
+}
+
+static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
 
        switch (cmd) {
        case CLI_INIT:
@@ -2748,42 +3148,128 @@ static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct
                return NULL;
        }
 
-       if (a->argc != 3)
+       return _skinny_show_devices(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
+}
+
+static char *_skinny_show_device(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
+{
+       struct skinny_device *d;
+       struct skinny_line *l;
+       struct skinny_speeddial *sd;
+       struct skinny_addon *sa;
+       char codec_buf[512];
+
+       if (argc < 4) {
                return CLI_SHOWUSAGE;
+       }
 
-       ast_mutex_lock(&devicelock);
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE(&devices, d, list) {
+               if (!strcasecmp(argv[3], d->id) || !strcasecmp(argv[3], d->name)) {
+                       int numlines = 0, numaddons = 0, numspeeddials = 0;
 
-       ast_cli(a->fd, "Name                 DeviceId         IP              Type            R NL\n");
-       ast_cli(a->fd, "-------------------- ---------------- --------------- --------------- - --\n");
+                       AST_LIST_TRAVERSE(&d->lines, l, list){
+                               numlines++;
+                       }
 
-       for (d = devices; d; d = d->next) {
-               int numlines = 0;
+                       AST_LIST_TRAVERSE(&d->addons, sa, list) {
+                               numaddons++;
+                       }
 
-               for (l = d->lines; l; l = l->next)
-                       numlines++;
-               
-               ast_cli(a->fd, "%-20s %-16s %-15s %-15s %c %2d\n",
-                       d->name,
-                       d->id,
-                       d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
-                       device2str(d->type),
-                       d->registered?'Y':'N',
-                       numlines);
+                       AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
+                               numspeeddials++;
+                       }
+
+                       if (type == 0) { /* CLI */
+                               ast_cli(fd, "Name:        %s\n", d->name);
+                               ast_cli(fd, "Id:          %s\n", d->id);
+                               ast_cli(fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
+                               ast_cli(fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
+                               ast_cli(fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
+                               ast_cli(fd, "Device Type: %s\n", device2str(d->type));
+                               ast_cli(fd, "Conf Codecs:");
+                               ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->confcapability);
+                               ast_cli(fd, "%s\n", codec_buf);
+                               ast_cli(fd, "Neg Codecs: ");
+                               ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->capability);
+                               ast_cli(fd, "%s\n", codec_buf);
+                               ast_cli(fd, "Registered:  %s\n", (d->registered ? "Yes" : "No"));
+                               ast_cli(fd, "Lines:       %d\n", numlines);
+                               AST_LIST_TRAVERSE(&d->lines, l, list) {
+                                       ast_cli(fd, "  %s (%s)\n", l->name, l->label);
+                               }
+                               AST_LIST_TRAVERSE(&d->addons, sa, list) {
+                                       numaddons++;
+                               }       
+                               ast_cli(fd, "Addons:      %d\n", numaddons);
+                               AST_LIST_TRAVERSE(&d->addons, sa, list) {
+                                       ast_cli(fd, "  %s\n", sa->type);
+                               }
+                               AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
+                                       numspeeddials++;
+                               }
+                               ast_cli(fd, "Speeddials:  %d\n", numspeeddials);
+                               AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
+                                       ast_cli(fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
+                               }
+                       } else { /* manager */
+                               astman_append(s, "Channeltype: SKINNY\r\n");
+                               astman_append(s, "ObjectName: %s\r\n", d->name);
+                               astman_append(s, "ChannelObjectType: device\r\n");
+                               astman_append(s, "Id: %s\r\n", d->id);
+                               astman_append(s, "version: %s\r\n", S_OR(d->version_id, "Unknown"));
+                               astman_append(s, "Ipaddress: %s\r\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
+                               astman_append(s, "Port: %d\r\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
+                               astman_append(s, "DeviceType: %s\r\n", device2str(d->type));
+                               astman_append(s, "Codecs: ");
+                               ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->confcapability);
+                               astman_append(s, "%s\r\n", codec_buf);
+                               astman_append(s, "CodecOrder: ");
+                               ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->capability);
+                               astman_append(s, "%s\r\n", codec_buf);
+                               astman_append(s, "Devicestatus: %s\r\n", (d->registered?"registered":"unregistered"));
+                               astman_append(s, "NumberOfLines: %d\r\n", numlines);
+                               AST_LIST_TRAVERSE(&d->lines, l, list) {
+                                       astman_append(s, "Line: %s (%s)\r\n", l->name, l->label);
+                               }
+                               astman_append(s, "NumberOfAddons: %d\r\n", numaddons);
+                               AST_LIST_TRAVERSE(&d->addons, sa, list) {
+                                       astman_append(s, "Addon: %s\r\n", sa->type);
+                               }
+                               astman_append(s, "NumberOfSpeeddials: %d\r\n", numspeeddials);
+                               AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
+                                       astman_append(s, "Speeddial: %s (%s) ishint: %d\r\n", sd->exten, sd->label, sd->isHint);
+                               }
+                       }
+               }
        }
+       AST_LIST_UNLOCK(&devices);
+       return CLI_SUCCESS;
+}
 
-       ast_mutex_unlock(&devicelock);
+static int manager_skinny_show_device(struct mansession *s, const struct message *m)
+{
+       const char *a[4];
+       const char *device;
 
-       return CLI_SUCCESS;
+       device = astman_get_header(m, "Device");
+       if (ast_strlen_zero(device)) {
+               astman_send_error(s, m, "Device: <name> missing.");
+               return 0;
+       }
+       a[0] = "skinny";
+       a[1] = "show";
+       a[2] = "device";
+       a[3] = device;
+
+       _skinny_show_device(1, -1, s, m, 4, a);
+       astman_append(s, "\r\n\r\n" );
+       return 0;
 }
 
 /*! \brief Show device information */
 static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       struct skinny_device *d;
-       struct skinny_line *l;
-       struct skinny_speeddial *sd;
-       struct skinny_addon *sa;
-
        switch (cmd) {
        case CLI_INIT:
                e->command = "skinny show device";
@@ -2795,468 +3281,392 @@ static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct
                return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
        }
 
-       if (a->argc < 4)
-               return CLI_SHOWUSAGE;
+       return _skinny_show_device(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
+}
 
-       ast_mutex_lock(&devicelock);
-       for (d = devices; d; d = d->next) {
-               if (!strcasecmp(a->argv[3], d->id) || !strcasecmp(a->argv[3], d->name)) {
-                       int numlines = 0, numaddons = 0, numspeeddials = 0;
+static char *_skinny_show_lines(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
+{
+       struct skinny_line *l;
+       struct skinny_subchannel *sub;
+       int total_lines = 0;
+       int verbose = 0;
+       const char *id;
+       char idtext[256] = "";
 
-                       for (l = d->lines; l; l = l->next)
-                               numlines++;
+       if (s) {        /* Manager - get ActionID */
+               id = astman_get_header(m, "ActionID");
+               if (!ast_strlen_zero(id))
+                       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
+       }
 
-                       ast_cli(a->fd, "Name:        %s\n", d->name);
-                       ast_cli(a->fd, "Id:          %s\n", d->id);
-                       ast_cli(a->fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
-                       ast_cli(a->fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
-                       ast_cli(a->fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
-                       ast_cli(a->fd, "Device Type: %s\n", device2str(d->type));
-                       ast_cli(a->fd, "Registered:  %s\n", (d->registered ? "Yes" : "No"));
-                       ast_cli(a->fd, "Lines:       %d\n", numlines);
-                       for (l = d->lines; l; l = l->next)
-                               ast_cli(a->fd, "  %s (%s)\n", l->name, l->label);
-                       for (sa = d->addons; sa; sa = sa->next)
-                               numaddons++;
-                       ast_cli(a->fd, "Addons:      %d\n", numaddons);
-                       for (sa = d->addons; sa; sa = sa->next)
-                               ast_cli(a->fd, "  %s\n", sa->type);
-                       for (sd = d->speeddials; sd; sd = sd->next)
-                               numspeeddials++;
-                       ast_cli(a->fd, "Speeddials:  %d\n", numspeeddials);
-                       for (sd = d->speeddials; sd; sd = sd->next)
-                               ast_cli(a->fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
+       switch (argc) {
+       case 4:
+               verbose = 1;
+               break;
+       case 3:
+               verbose = 0;
+               break;
+       default:
+               return CLI_SHOWUSAGE;
+       }
+
+       if (!s) {
+               ast_cli(fd, "Name                 Device Name          Instance Label               \n");
+               ast_cli(fd, "-------------------- -------------------- -------- --------------------\n");
+       }
+       AST_LIST_LOCK(&lines);
+       AST_LIST_TRAVERSE(&lines, l, all) {
+               total_lines++;
+               if (!s) {
+                       ast_cli(fd, "%-20s %-20s %8d %-20s\n",
+                               l->name,
+                               (l->device ? l->device->name : "Not connected"),
+                               l->instance,
+                               l->label);
+                       if (verbose) {
+                               AST_LIST_TRAVERSE(&l->sub, sub, list) {
+                                       ast_cli(fd, "  %s> %s to %s\n",
+                                               (sub == l->activesub?"Active  ":"Inactive"),
+                                               sub->owner->name,
+                                               (ast_bridged_channel(sub->owner)?ast_bridged_channel(sub->owner)->name:"")
+                                       );
+                               }
+                       }
+               } else {
+                       astman_append(s,
+                               "Event: LineEntry\r\n%s"
+                               "Channeltype: SKINNY\r\n"
+                               "ObjectName: %s\r\n"
+                               "ChannelObjectType: line\r\n"
+                               "Device: %s\r\n"
+                               "Instance: %d\r\n"
+                               "Label: %s\r\n",
+                               idtext,
+                               l->name,
+                               (l->device?l->device->name:"None"),
+                               l->instance,
+                               l->label);
                }
+               AST_LIST_UNLOCK(&lines);
        }
-       ast_mutex_unlock(&devicelock);
+
+       if (total) {
+               *total = total_lines;
+       }
+
        return CLI_SUCCESS;
 }
 
+/*! \brief  Show Skinny lines in the manager API */
+/*    Inspired from chan_sip */
+static int manager_skinny_show_lines(struct mansession *s, const struct message *m)
+{
+       const char *id = astman_get_header(m, "ActionID");
+       const char *a[] = {"skinny", "show", "lines"};
+       char idtext[256] = "";
+       int total = 0;
+
+       if (!ast_strlen_zero(id))
+               snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
+
+       astman_send_listack(s, m, "Line status list will follow", "start");
+       /* List the lines in separate manager events */
+       _skinny_show_lines(-1, &total, s, m, 3, a);
+       /* Send final confirmation */
+       astman_append(s,
+       "Event: LinelistComplete\r\n"
+       "EventList: Complete\r\n"
+       "ListItems: %d\r\n"
+       "%s"
+       "\r\n", total, idtext);
+       return 0;
+}
+
 static char *handle_skinny_show_lines(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       struct skinny_device *d;
-       struct skinny_line *l;
+       int verbose = 0;
 
        switch (cmd) {
        case CLI_INIT:
-               e->command = "skinny show lines";
+               e->command = "skinny show lines [verbose]";
                e->usage =
                        "Usage: skinny show lines\n"
-                       "       Lists all lines known to the Skinny subsystem.\n";
+                       "       Lists all lines known to the Skinny subsystem.\n"
+                       "       If 'verbose' is specified, the output includes\n"
+                       "       information about subs for each line.\n";
                return NULL;
        case CLI_GENERATE:
                return NULL;
        }
 
-       if (a->argc != 3)
-               return CLI_SHOWUSAGE;
-       
-       ast_mutex_lock(&devicelock);
-       
-       ast_cli(a->fd, "Device Name          Instance Name                 Label               \n");
-       ast_cli(a->fd, "-------------------- -------- -------------------- --------------------\n");
-       for (d = devices; d; d = d->next) {
-               for (l = d->lines; l; l = l->next) {
-                       ast_cli(a->fd, "%-20s %8d %-20s %-20s\n",
-                               d->name,
-                               l->instance,
-                               l->name,
-                               l->label);
+       if (a->argc == e->args) {
+               if (!strcasecmp(a->argv[e->args-1], "verbose")) {
+                       verbose = 1;
+               } else {
+                       return CLI_SHOWUSAGE;
                }
+       } else if (a->argc != e->args - 1) {
+               return CLI_SHOWUSAGE;
        }
-       
-       ast_mutex_unlock(&devicelock);
-       return CLI_SUCCESS;
+
+       return _skinny_show_lines(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
 }
 
-/*! \brief List line information. */
-static char *handle_skinny_show_line(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static char *_skinny_show_line(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
 {
        struct skinny_device *d;
        struct skinny_line *l;
+       struct ast_codec_pref *pref;
+       int x = 0, codec = 0;
        char codec_buf[512];
        char group_buf[256];
+       char cbuf[256];
 
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "skinny show line";
-               e->usage =
-                       "Usage: skinny show line <Line> [ on <DeviceID|DeviceName> ]\n"
-                       "       List all lineinformation of a specific line known to the Skinny subsystem.\n";
-               return NULL;
-       case CLI_GENERATE:
-               return complete_skinny_show_line(a->line, a->word, a->pos, a->n);
+       switch (argc) {
+       case 4:
+               break;
+       case 6:
+               break;
+       default:
+               return CLI_SHOWUSAGE;
        }
 
-       if (a->argc < 4)
-               return CLI_SHOWUSAGE;
-       
-       ast_mutex_lock(&devicelock);
+       AST_LIST_LOCK(&devices);
 
        /* Show all lines matching the one supplied */
-       for (d = devices; d; d = d->next) {
-               if (a->argc == 6 && (strcasecmp(a->argv[5], d->id) && strcasecmp(a->argv[5], d->name)))
+       AST_LIST_TRAVERSE(&devices, d, list) {
+               if (argc == 6 && (strcasecmp(argv[5], d->id) && strcasecmp(argv[5], d->name))) {
                        continue;
-               for (l = d->lines; l; l = l->next) {
-                       if (strcasecmp(a->argv[3], l->name))
+               }
+               AST_LIST_TRAVERSE(&d->lines, l, list) {
+                       if (strcasecmp(argv[3], l->name)) {
                                continue;
-                       ast_cli(a->fd, "Line:             %s\n", l->name);
-                       ast_cli(a->fd, "On Device:        %s\n", d->name);
-                       ast_cli(a->fd, "Line Label:       %s\n", l->label);
-                       ast_cli(a->fd, "Extension:        %s\n", S_OR(l->exten, "<not set>"));
-                       ast_cli(a->fd, "Context:          %s\n", l->context);
-                       ast_cli(a->fd, "CallGroup:        %s\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
-                       ast_cli(a->fd, "PickupGroup:      %s\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
-                       ast_cli(a->fd, "Language:         %s\n", S_OR(l->language, "<not set>"));
-                       ast_cli(a->fd, "Accountcode:      %s\n", S_OR(l->accountcode, "<not set>"));
-                       ast_cli(a->fd, "AmaFlag:          %s\n", ast_cdr_flags2str(l->amaflags));
-                       ast_cli(a->fd, "CallerId Number:  %s\n", S_OR(l->cid_num, "<not set>"));
-                       ast_cli(a->fd, "CallerId Name:    %s\n", S_OR(l->cid_name, "<not set>"));
-                       ast_cli(a->fd, "Hide CallerId:    %s\n", (l->hidecallerid ? "Yes" : "No"));
-                       ast_cli(a->fd, "CFwdAll:          %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
-                       ast_cli(a->fd, "CFwdBusy:         %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
-                       ast_cli(a->fd, "CFwdNoAnswer:     %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
-                       ast_cli(a->fd, "VoicemailBox:     %s\n", S_OR(l->mailbox, "<not set>"));
-                       ast_cli(a->fd, "VoicemailNumber:  %s\n", S_OR(l->vmexten, "<not set>"));
-                       ast_cli(a->fd, "MWIblink:         %d\n", l->mwiblink);
-                       ast_cli(a->fd, "Regextension:     %s\n", S_OR(l->regexten, "<not set>"));
-                       ast_cli(a->fd, "Regcontext:       %s\n", S_OR(l->regcontext, "<not set>"));
-                       ast_cli(a->fd, "MoHInterpret:     %s\n", S_OR(l->mohinterpret, "<not set>"));
-                       ast_cli(a->fd, "MoHSuggest:       %s\n", S_OR(l->mohsuggest, "<not set>"));
-                       ast_cli(a->fd, "Last dialed nr:   %s\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
-                       ast_cli(a->fd, "Last CallerID:    %s\n", S_OR(l->lastcallerid, "<not set>"));
-                       ast_cli(a->fd, "Transfer enabled: %s\n", (l->transfer ? "Yes" : "No"));
-                       ast_cli(a->fd, "Callwaiting:      %s\n", (l->callwaiting ? "Yes" : "No"));
-                       ast_cli(a->fd, "3Way Calling:     %s\n", (l->threewaycalling ? "Yes" : "No"));
-                       ast_cli(a->fd, "Can forward:      %s\n", (l->cancallforward ? "Yes" : "No"));
-                       ast_cli(a->fd, "Do Not Disturb:   %s\n", (l->dnd ? "Yes" : "No"));
-                       ast_cli(a->fd, "NAT:              %s\n", (l->nat ? "Yes" : "No"));
-                       ast_cli(a->fd, "immediate:        %s\n", (l->immediate ? "Yes" : "No"));
-                       ast_cli(a->fd, "Group:            %d\n", l->group);
-                       ast_cli(a->fd, "Codecs:           ");
-                       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->capability);
-                       ast_cli(a->fd, "%s\n", codec_buf);
-                       ast_cli(a->fd, "Codec Order:      (");
-                       print_codec_to_cli(a->fd, &l->prefs);
-                       ast_cli(a->fd, ")\n");
-                       ast_cli(a->fd, "\n");
+                       }
+                       if (type == 0) { /* CLI */
+                               ast_cli(fd, "Line:             %s\n", l->name);
+                               ast_cli(fd, "On Device:        %s\n", d->name);
+                               ast_cli(fd, "Line Label:       %s\n", l->label);
+                               ast_cli(fd, "Extension:        %s\n", S_OR(l->exten, "<not set>"));
+                               ast_cli(fd, "Context:          %s\n", l->context);
+                               ast_cli(fd, "CallGroup:        %s\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
+                               ast_cli(fd, "PickupGroup:      %s\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
+                               ast_cli(fd, "Language:         %s\n", S_OR(l->language, "<not set>"));
+                               ast_cli(fd, "Accountcode:      %s\n", S_OR(l->accountcode, "<not set>"));
+                               ast_cli(fd, "AmaFlag:          %s\n", ast_cdr_flags2str(l->amaflags));
+                               ast_cli(fd, "CallerId Number:  %s\n", S_OR(l->cid_num, "<not set>"));
+                               ast_cli(fd, "CallerId Name:    %s\n", S_OR(l->cid_name, "<not set>"));
+                               ast_cli(fd, "Hide CallerId:    %s\n", (l->hidecallerid ? "Yes" : "No"));
+                               ast_cli(fd, "CFwdAll:          %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
+                               ast_cli(fd, "CFwdBusy:         %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
+                               ast_cli(fd, "CFwdNoAnswer:     %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
+                               ast_cli(fd, "VoicemailBox:     %s\n", S_OR(l->mailbox, "<not set>"));
+                               ast_cli(fd, "VoicemailNumber:  %s\n", S_OR(l->vmexten, "<not set>"));
+                               ast_cli(fd, "MWIblink:         %d\n", l->mwiblink);
+                               ast_cli(fd, "Regextension:     %s\n", S_OR(l->regexten, "<not set>"));
+                               ast_cli(fd, "Regcontext:       %s\n", S_OR(l->regcontext, "<not set>"));
+                               ast_cli(fd, "MoHInterpret:     %s\n", S_OR(l->mohinterpret, "<not set>"));
+                               ast_cli(fd, "MoHSuggest:       %s\n", S_OR(l->mohsuggest, "<not set>"));
+                               ast_cli(fd, "Last dialed nr:   %s\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
+                               ast_cli(fd, "Last CallerID:    %s\n", S_OR(l->lastcallerid, "<not set>"));
+                               ast_cli(fd, "Transfer enabled: %s\n", (l->transfer ? "Yes" : "No"));
+                               ast_cli(fd, "Callwaiting:      %s\n", (l->callwaiting ? "Yes" : "No"));
+                               ast_cli(fd, "3Way Calling:     %s\n", (l->threewaycalling ? "Yes" : "No"));
+                               ast_cli(fd, "Can forward:      %s\n", (l->cancallforward ? "Yes" : "No"));
+                               ast_cli(fd, "Do Not Disturb:   %s\n", (l->dnd ? "Yes" : "No"));
+                               ast_cli(fd, "NAT:              %s\n", (l->nat ? "Yes" : "No"));
+                               ast_cli(fd, "immediate:        %s\n", (l->immediate ? "Yes" : "No"));
+                               ast_cli(fd, "Group:            %d\n", l->group);
+                               ast_cli(fd, "Parkinglot:       %s\n", S_OR(l->parkinglot, "<not set>"));
+                               ast_cli(fd, "Conf Codecs:      ");
+                               ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->confcapability);
+                               ast_cli(fd, "%s\n", codec_buf);
+                               ast_cli(fd, "Neg Codecs:       ");
+                               ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->capability);
+                               ast_cli(fd, "%s\n", codec_buf);
+                               ast_cli(fd, "Codec Order:      (");
+                               print_codec_to_cli(fd, &l->prefs);
+                               ast_cli(fd, ")\n");
+                               ast_cli(fd, "\n");
+                       } else { /* manager */
+                               astman_append(s, "Channeltype: SKINNY\r\n");
+                               astman_append(s, "ObjectName: %s\r\n", l->name);
+                               astman_append(s, "ChannelObjectType: line\r\n");
+                               astman_append(s, "Device: %s\r\n", d->name);
+                               astman_append(s, "LineLabel: %s\r\n", l->label);
+                               astman_append(s, "Extension: %s\r\n", S_OR(l->exten, "<not set>"));
+                               astman_append(s, "Context: %s\r\n", l->context);
+                               astman_append(s, "CallGroup: %s\r\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
+                               astman_append(s, "PickupGroup: %s\r\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
+                               astman_append(s, "Language: %s\r\n", S_OR(l->language, "<not set>"));
+                               astman_append(s, "Accountcode: %s\r\n", S_OR(l->accountcode, "<not set>"));
+                               astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(l->amaflags));
+                               astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), l->cid_name, l->cid_num, ""));
+                               astman_append(s, "HideCallerId: %s\r\n", (l->hidecallerid ? "Yes" : "No"));
+                               astman_append(s, "CFwdAll: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
+                               astman_append(s, "CFwdBusy: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
+                               astman_append(s, "CFwdNoAnswer: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
+                               astman_append(s, "VoicemailBox: %s\r\n", S_OR(l->mailbox, "<not set>"));
+                               astman_append(s, "VoicemailNumber: %s\r\n", S_OR(l->vmexten, "<not set>"));
+                               astman_append(s, "MWIblink: %d\r\n", l->mwiblink);
+                               astman_append(s, "RegExtension: %s\r\n", S_OR(l->regexten, "<not set>"));
+                               astman_append(s, "Regcontext: %s\r\n", S_OR(l->regcontext, "<not set>"));
+                               astman_append(s, "MoHInterpret: %s\r\n", S_OR(l->mohinterpret, "<not set>"));
+                               astman_append(s, "MoHSuggest: %s\r\n", S_OR(l->mohsuggest, "<not set>"));
+                               astman_append(s, "LastDialedNr: %s\r\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
+                               astman_append(s, "LastCallerID: %s\r\n", S_OR(l->lastcallerid, "<not set>"));
+                               astman_append(s, "Transfer: %s\r\n", (l->transfer ? "Yes" : "No"));
+                               astman_append(s, "Callwaiting: %s\r\n", (l->callwaiting ? "Yes" : "No"));
+                               astman_append(s, "3WayCalling: %s\r\n", (l->threewaycalling ? "Yes" : "No"));
+                               astman_append(s, "CanForward: %s\r\n", (l->cancallforward ? "Yes" : "No"));
+                               astman_append(s, "DoNotDisturb: %s\r\n", (l->dnd ? "Yes" : "No"));
+                               astman_append(s, "NAT: %s\r\n", (l->nat ? "Yes" : "No"));
+                               astman_append(s, "immediate: %s\r\n", (l->immediate ? "Yes" : "No"));
+                               astman_append(s, "Group: %d\r\n", l->group);
+                               astman_append(s, "Parkinglot: %s\r\n", S_OR(l->parkinglot, "<not set>"));
+                               ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->confcapability);
+                               astman_append(s, "Codecs: %s\r\n", codec_buf);
+                               astman_append(s, "CodecOrder: ");
+                               pref = &l->prefs;
+                               for(x = 0; x < 32 ; x++) {
+                                       codec = ast_codec_pref_index(pref, x);
+                                       if (!codec)
+                                               break;
+                                       astman_append(s, "%s", ast_getformatname(codec));
+                                       if (x < 31 && ast_codec_pref_index(pref, x+1))
+                                               astman_append(s, ",");
+                               }
+                               astman_append(s, "\r\n");
+                       }
                }
        }
        
-       ast_mutex_unlock(&devicelock);
+       AST_LIST_UNLOCK(&devices);
        return CLI_SUCCESS;
 }
 
-/*! \brief List global settings for the Skinny subsystem. */
-static char *handle_skinny_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static int manager_skinny_show_line(struct mansession *s, const struct message *m)
+{
+       const char *a[4];
+       const char *line;
+
+       line = astman_get_header(m, "Line");
+       if (ast_strlen_zero(line)) {
+               astman_send_error(s, m, "Line: <name> missing.");
+               return 0;
+       }
+       a[0] = "skinny";
+       a[1] = "show";
+       a[2] = "line";
+       a[3] = line;
+
+       _skinny_show_line(1, -1, s, m, 4, a);
+       astman_append(s, "\r\n\r\n" );
+       return 0;
+}
+
+/*! \brief List line information. */
+static char *handle_skinny_show_line(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        switch (cmd) {
        case CLI_INIT:
-               e->command = "skinny show settings";
+               e->command = "skinny show line";
                e->usage =
-                       "Usage: skinny show settings\n"
-                       "       Lists all global configuration settings of the Skinny subsystem.\n";
+                       "Usage: skinny show line <Line> [ on <DeviceID|DeviceName> ]\n"
+                       "       List all lineinformation of a specific line known to the Skinny subsystem.\n";
                return NULL;
        case CLI_GENERATE:
-               return NULL;
-       }       
-
-       if (a->argc != 3)
-               return CLI_SHOWUSAGE;
-
-       ast_cli(a->fd, "\nGlobal Settings:\n");
-       ast_cli(a->fd, "  Skinny Port:            %d\n", ntohs(bindaddr.sin_port));
-       ast_cli(a->fd, "  Bindaddress:            %s\n", ast_inet_ntoa(bindaddr.sin_addr));
-       ast_cli(a->fd, "  KeepAlive:              %d\n", keep_alive);
-       ast_cli(a->fd, "  Date Format:            %s\n", date_format);
-       ast_cli(a->fd, "  Voice Mail Extension:   %s\n", S_OR(vmexten, "(not set)"));
-       ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(regcontext, "(not set)"));
-       ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", (ast_test_flag(&global_jbconf, AST_JB_ENABLED) ? "Yes" : "No"));
-       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", (ast_test_flag(&global_jbconf, AST_JB_FORCED) ? "Yes" : "No"));
-       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
-       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
-       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
-       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", (ast_test_flag(&global_jbconf, AST_JB_LOG) ? "Yes" : "No"));
+               return complete_skinny_show_line(a->line, a->word, a->pos, a->n);
+       }
 
-       return CLI_SUCCESS;
+       return _skinny_show_line(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
 }
 
-static struct ast_cli_entry cli_skinny_set_debug_deprecated = AST_CLI_DEFINE(handle_skinny_set_debug_deprecated, "Enable/Disable Skinny debugging");
-static struct ast_cli_entry cli_skinny[] = {
-       AST_CLI_DEFINE(handle_skinny_show_devices, "List defined Skinny devices"),
-       AST_CLI_DEFINE(handle_skinny_show_device, "List Skinny device information"),
-       AST_CLI_DEFINE(handle_skinny_show_lines, "List defined Skinny lines per device"),
-       AST_CLI_DEFINE(handle_skinny_show_line, "List Skinny line information"),
-       AST_CLI_DEFINE(handle_skinny_show_settings, "List global Skinny settings"),
-       AST_CLI_DEFINE(handle_skinny_set_debug, "Enable/Disable Skinny debugging", .deprecate_cmd = &cli_skinny_set_debug_deprecated),
-       AST_CLI_DEFINE(handle_skinny_reset, "Reset Skinny device(s)"),
-};
-
-static struct skinny_device *build_device(const char *cat, struct ast_variable *v)
+/*! \brief List global settings for the Skinny subsystem. */
+static char *handle_skinny_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       struct skinny_device *d;
-       struct skinny_line *l;
-       struct skinny_speeddial *sd;
-       struct skinny_addon *a;
-       char device_vmexten[AST_MAX_EXTENSION];
-       struct ast_variable *chanvars = NULL;
-       int lineInstance = 1;
-       int speeddialInstance = 1;
-       int y = 0;
-
-       if (!(d = ast_calloc(1, sizeof(*d)))) {
-               return NULL;
-       } else {
-               ast_copy_string(d->name, cat, sizeof(d->name));
-               d->lastlineinstance = 1;
-               d->capability = default_capability;
-               d->prefs = default_prefs;
-               if (!ast_strlen_zero(vmexten))
-                       ast_copy_string(device_vmexten, vmexten, sizeof(device_vmexten));
-               else
-                       memset(device_vmexten, 0, sizeof(device_vmexten));
-
-               d->earlyrtp = 1;
-               while(v) {
-                       if (!strcasecmp(v->name, "host")) {
-                               if (ast_get_ip(&d->addr, v->value)) {
-                                       ast_free(d);
-                                       return NULL;
-                               }
-                       } else if (!strcasecmp(v->name, "port")) {
-                               d->addr.sin_port = htons(atoi(v->value));
-                       } else if (!strcasecmp(v->name, "device")) {
-                               ast_copy_string(d->id, v->value, sizeof(d->id));
-                       } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
-                               d->ha = ast_append_ha(v->name, v->value, d->ha, NULL);
-                       } else if (!strcasecmp(v->name, "vmexten")) {
-                               ast_copy_string(device_vmexten, v->value, sizeof(device_vmexten));
-                       } else if (!strcasecmp(v->name, "context")) {
-                               ast_copy_string(context, v->value, sizeof(context));
-                       } else if (!strcasecmp(v->name, "regexten")) {
-                               ast_copy_string(regexten, v->value, sizeof(regexten));
-                       } else if (!strcasecmp(v->name, "allow")) {
-                               ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 1);
-                       } else if (!strcasecmp(v->name, "disallow")) {
-                               ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 0);
-                       } else if (!strcasecmp(v->name, "version")) {
-                               ast_copy_string(d->version_id, v->value, sizeof(d->version_id));
-                       } else if (!strcasecmp(v->name, "canreinvite")) {
-                               canreinvite = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "earlyrtp")) {
-                               d->earlyrtp = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "nat")) {
-                               nat = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "callerid")) {
-                               if (!strcasecmp(v->value, "asreceived")) {
-                                       cid_num[0] = '\0';
-                                       cid_name[0] = '\0';
-                               } else {
-                                       ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
-                               }
-                       } else if (!strcasecmp(v->name, "language")) {
-                               ast_copy_string(language, v->value, sizeof(language));
-                       } else if (!strcasecmp(v->name, "accountcode")) {
-                               ast_copy_string(accountcode, v->value, sizeof(accountcode));
-                       } else if (!strcasecmp(v->name, "amaflags")) {
-                               y = ast_cdr_amaflags2int(v->value);
-                               if (y < 0) {
-                                       ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
-                               } else {
-                                       amaflags = y;
-                               }
-                       } else if (!strcasecmp(v->name, "mohinterpret") || !strcasecmp(v->name, "musiconhold")) {
-                               ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
-                       } else if (!strcasecmp(v->name, "mohsuggest")) {
-                               ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
-                       } else if (!strcasecmp(v->name, "callgroup")) {
-                               cur_callergroup = ast_get_group(v->value);
-                       } else if (!strcasecmp(v->name, "pickupgroup")) {
-                               cur_pickupgroup = ast_get_group(v->value);
-                       } else if (!strcasecmp(v->name, "immediate")) {
-                               immediate = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "cancallforward")) {
-                               cancallforward = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "mailbox")) {
-                               ast_copy_string(mailbox, v->value, sizeof(mailbox));
-                       } else if (!strcasecmp(v->name, "hasvoicemail")) {
-                               if (ast_true(v->value) && ast_strlen_zero(mailbox)) {
-                                       ast_copy_string(mailbox, cat, sizeof(mailbox));
-                               }
-                       } else if (!strcasecmp(v->name, "callreturn")) {
-                               callreturn = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "callwaiting")) {
-                               callwaiting = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "transfer")) {
-                               transfer = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "threewaycalling")) {
-                               threewaycalling = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "mwiblink")) {
-                               mwiblink = ast_true(v->value);
-                       } else if (!strcasecmp(v->name, "linelabel")) {
-                               ast_copy_string(linelabel, v->value, sizeof(linelabel));
-                       } else if (!strcasecmp(v->name, "setvar")) {
-                               chanvars = add_var(v->value, chanvars);
-                       } else if ( !strcasecmp(v->name, "parkinglot")) {
-                               ast_copy_string(parkinglot, v->value, sizeof(parkinglot));
-                       } else if (!strcasecmp(v->name, "speeddial")) {
-                               if (!(sd = ast_calloc(1, sizeof(*sd)))) {
-                                       return NULL;
-                               } else {
-                                       char buf[256];
-                                       char *stringp = buf, *exten, *context, *label;
-
-                                       ast_copy_string(buf, v->value, sizeof(buf));
-                                       exten = strsep(&stringp, ",");
-                                       if ((context = strchr(exten, '@'))) {
-                                               *context++ = '\0';
-                                       }
-                                       label = stringp;
-                                       ast_mutex_init(&sd->lock);
-                                       ast_copy_string(sd->exten, exten, sizeof(sd->exten));
-                                       if (!ast_strlen_zero(context)) {
-                                               sd->isHint = 1;
-                                               sd->instance = lineInstance++;
-                                               ast_copy_string(sd->context, context, sizeof(sd->context));
-                                       } else {
-                                               sd->isHint = 0;
-                                               sd->instance = speeddialInstance++;
-                                               sd->context[0] = '\0';
-                                       }
-                                       ast_copy_string(sd->label, S_OR(label, exten), sizeof(sd->label));
-
-                                       sd->parent = d;
-
-                                       sd->next = d->speeddials;
-                                       d->speeddials = sd;
-                               }
-                       } else if (!strcasecmp(v->name, "addon")) {
-                               if (!(a = ast_calloc(1, sizeof(*a)))) {
-                                       return NULL;
-                               } else {
-                                       ast_mutex_init(&a->lock);
-                                       ast_copy_string(a->type, v->value, sizeof(a->type));
-
-                                       a->next = d->addons;
-                                       d->addons = a;
-                               }
-                       } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
-                               if (!(l = ast_calloc(1, sizeof(*l)))) {
-                                       return NULL;
-                               } else {
-                                       ast_mutex_init(&l->lock);
-                                       ast_copy_string(l->name, v->value, sizeof(l->name));
-
-                                       /* XXX Should we check for uniqueness?? XXX */
-                                       ast_copy_string(l->context, context, sizeof(l->context));
-                                       ast_copy_string(l->cid_num, cid_num, sizeof(l->cid_num));
-                                       ast_copy_string(l->cid_name, cid_name, sizeof(l->cid_name));
-                                       ast_copy_string(l->label, linelabel, sizeof(l->label));
-                                       ast_copy_string(l->parkinglot, parkinglot, sizeof(l->parkinglot));
-                                       ast_copy_string(l->language, language, sizeof(l->language));
-                                       ast_copy_string(l->mohinterpret, mohinterpret, sizeof(l->mohinterpret));
-                                       ast_copy_string(l->mohsuggest, mohsuggest, sizeof(l->mohsuggest));
-                                       ast_copy_string(l->regexten, regexten, sizeof(l->regexten));
-                                       ast_copy_string(l->mailbox, mailbox, sizeof(l->mailbox));
-                                       if (!ast_strlen_zero(mailbox)) {
-                                               char *cfg_mailbox, *cfg_context;
-                                               cfg_context = cfg_mailbox = ast_strdupa(l->mailbox);
-                                               ast_verb(3, "Setting mailbox '%s' on %s@%s\n", cfg_mailbox, d->name, l->name);
-                                               strsep(&cfg_context, "@");
-                                               if (ast_strlen_zero(cfg_context))
-                                                        cfg_context = "default";
-                                               l->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, NULL,
-                                                       AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, cfg_mailbox,
-                                                       AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, cfg_context,
-                                                       AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
-                                                       AST_EVENT_IE_END);
-                                       }
-                                       ast_copy_string(l->vmexten, device_vmexten, sizeof(vmexten));
-                                       l->chanvars = chanvars;
-                                       l->msgstate = -1;
-                                       l->capability = d->capability;
-                                       l->prefs = d->prefs;
-                                       l->parent = d;
-                                       if (!strcasecmp(v->name, "trunk")) {
-                                               l->type = TYPE_TRUNK;
-                                       } else {
-                                               l->type = TYPE_LINE;
-                                       }
-                                       l->immediate = immediate;
-                                       l->callgroup = cur_callergroup;
-                                       l->pickupgroup = cur_pickupgroup;
-                                       l->callreturn = callreturn;
-                                       l->cancallforward = cancallforward;
-                                       l->getforward = 0;
-                                       set_callforwards(l, NULL, 0);
-                                       l->callwaiting = callwaiting;
-                                       l->transfer = transfer;
-                                       l->threewaycalling = threewaycalling;
-                                       l->mwiblink = mwiblink;
-                                       l->onhooktime = time(NULL);
-                                       l->instance = lineInstance++;
-                                       /* ASSUME we're onhook at this point */
-                                       l->hookstate = SKINNY_ONHOOK;
-                                       l->nat = nat;
-                                       l->canreinvite = canreinvite;
-
-                                       if (!d->lines) {
-                                               d->activeline = l;
-                                       }
-                                       l->next = d->lines;
-                                       d->lines = l;
-                               }
-                       } else {
-                               ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
-                       }
-                       v = v->next;
-               }
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "skinny show settings";
+               e->usage =
+                       "Usage: skinny show settings\n"
+                       "       Lists all global configuration settings of the Skinny subsystem.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }       
 
-               if (!d->lines) {
-                       ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
-                       return NULL;
-               }
-               if (/*d->addr.sin_addr.s_addr && */!ntohs(d->addr.sin_port)) {
-                       d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
-               }
-       }
-       return d;
+       if (a->argc != 3)
+               return CLI_SHOWUSAGE;
+
+       ast_cli(a->fd, "\nGlobal Settings:\n");
+       ast_cli(a->fd, "  Skinny Port:            %d\n", ntohs(bindaddr.sin_port));
+       ast_cli(a->fd, "  Bindaddress:            %s\n", ast_inet_ntoa(bindaddr.sin_addr));
+       ast_cli(a->fd, "  KeepAlive:              %d\n", keep_alive);
+       ast_cli(a->fd, "  Date Format:            %s\n", date_format);
+       ast_cli(a->fd, "  Voice Mail Extension:   %s\n", S_OR(global_vmexten, "(not set)"));
+       ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(regcontext, "(not set)"));
+       ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", (ast_test_flag(&global_jbconf, AST_JB_ENABLED) ? "Yes" : "No"));
+       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", (ast_test_flag(&global_jbconf, AST_JB_FORCED) ? "Yes" : "No"));
+       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
+       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
+       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
+       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", (ast_test_flag(&global_jbconf, AST_JB_LOG) ? "Yes" : "No"));
+
+       return CLI_SUCCESS;
 }
 
+static struct ast_cli_entry cli_skinny[] = {
+       AST_CLI_DEFINE(handle_skinny_show_devices, "List defined Skinny devices"),
+       AST_CLI_DEFINE(handle_skinny_show_device, "List Skinny device information"),
+       AST_CLI_DEFINE(handle_skinny_show_lines, "List defined Skinny lines per device"),
+       AST_CLI_DEFINE(handle_skinny_show_line, "List Skinny line information"),
+       AST_CLI_DEFINE(handle_skinny_show_settings, "List global Skinny settings"),
+       AST_CLI_DEFINE(handle_skinny_set_debug, "Enable/Disable Skinny debugging"),
+       AST_CLI_DEFINE(handle_skinny_reset, "Reset Skinny device(s)"),
+       AST_CLI_DEFINE(handle_skinny_reload, "Reload Skinny config"),
+};
+
 static void start_rtp(struct skinny_subchannel *sub)
 {
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
+       struct skinny_device *d = l->device;
        int hasvideo = 0;
 
        ast_mutex_lock(&sub->lock);
        /* Allocate the RTP */
-       sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
+       sub->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr, NULL);
        if (hasvideo)
-               sub->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
-       
+               sub->vrtp = ast_rtp_instance_new("asterisk", sched, &bindaddr, NULL);
+
+       if (sub->rtp) {
+               ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_RTCP, 1);
+       }
+       if (sub->vrtp) {
+               ast_rtp_instance_set_prop(sub->vrtp, AST_RTP_PROPERTY_RTCP, 1);
+       }
+
        if (sub->rtp && sub->owner) {
-               ast_channel_set_fd(sub->owner, 0, ast_rtp_fd(sub->rtp));
-               ast_channel_set_fd(sub->owner, 1, ast_rtcp_fd(sub->rtp));
+               ast_channel_set_fd(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
+               ast_channel_set_fd(sub->owner, 1, ast_rtp_instance_fd(sub->rtp, 1));
        }
        if (hasvideo && sub->vrtp && sub->owner) {
-               ast_channel_set_fd(sub->owner, 2, ast_rtp_fd(sub->vrtp));
-               ast_channel_set_fd(sub->owner, 3, ast_rtcp_fd(sub->vrtp));
+               ast_channel_set_fd(sub->owner, 2, ast_rtp_instance_fd(sub->vrtp, 0));
+               ast_channel_set_fd(sub->owner, 3, ast_rtp_instance_fd(sub->vrtp, 1));
        }
        if (sub->rtp) {
-               ast_rtp_setqos(sub->rtp, tos_audio, cos_audio, "Skinny RTP");
-               ast_rtp_setnat(sub->rtp, l->nat);
+               ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "Skinny RTP");
+               ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, l->nat);
        }
        if (sub->vrtp) {
-               ast_rtp_setqos(sub->vrtp, tos_video, cos_video, "Skinny VRTP");
-               ast_rtp_setnat(sub->vrtp, l->nat);
+               ast_rtp_instance_set_qos(sub->vrtp, qos.tos_video, qos.cos_video, "Skinny VRTP");
+               ast_rtp_instance_set_prop(sub->vrtp, AST_RTP_PROPERTY_NAT, l->nat);
        }
        /* Set Frame packetization */
        if (sub->rtp)
-               ast_rtp_codec_setpref(sub->rtp, &l->prefs);
+               ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, &l->prefs);
 
        /* Create the RTP connection */
-       transmit_connect(d->session, sub);
+       transmit_connect(d, sub);
        ast_mutex_unlock(&sub->lock);
 }
 
@@ -3265,8 +3675,7 @@ static void *skinny_newcall(void *data)
        struct ast_channel *c = data;
        struct skinny_subchannel *sub = c->tech_pvt;
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
+       struct skinny_device *d = l->device;
        int res = 0;
 
        ast_copy_string(l->lastnumberdialed, c->exten, sizeof(l->lastnumberdialed));
@@ -3274,6 +3683,8 @@ static void *skinny_newcall(void *data)
                l->hidecallerid ? "" : l->cid_num,
                l->hidecallerid ? "" : l->cid_name,
                c->cid.cid_ani ? NULL : l->cid_num);
+       c->connected.id.number = ast_strdup(c->exten);
+       c->connected.id.name = NULL;
        ast_setstate(c, AST_STATE_RING);
        if (!sub->rtp) {
                start_rtp(sub);
@@ -3281,7 +3692,7 @@ static void *skinny_newcall(void *data)
        res = ast_pbx_run(c);
        if (res) {
                ast_log(LOG_WARNING, "PBX exited non-zero\n");
-               transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
+               transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
        }
        return NULL;
 }
@@ -3291,8 +3702,7 @@ static void *skinny_ss(void *data)
        struct ast_channel *c = data;
        struct skinny_subchannel *sub = c->tech_pvt;
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
+       struct skinny_device *d = l->device;
        int len = 0;
        int timeout = firstdigittimeout;
        int res = 0;
@@ -3318,7 +3728,7 @@ static void *skinny_ss(void *data)
                len = strlen(d->exten);
 
                if (!ast_ignore_pattern(c->context, d->exten)) {
-                       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+                       transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                }
                if (ast_exists_extension(c, c->context, d->exten, 1, l->cid_num)) {
                        if (!res || !ast_matchmore_extension(c, c->context, d->exten, 1, l->cid_num)) {
@@ -3327,10 +3737,10 @@ static void *skinny_ss(void *data)
                                        set_callforwards(l, d->exten, l->getforward);
                                        ast_verb(3, "Setting call forward (%d) to '%s' on channel %s\n",
                                                        l->cfwdtype, d->exten, c->name);
-                                       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                                       transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
-                                       transmit_displaynotify(s, "CFwd enabled", 10);
-                                       transmit_cfwdstate(s, l);
+                                       transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                                       transmit_lamp_indication(d, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
+                                       transmit_displaynotify(d, "CFwd enabled", 10);
+                                       transmit_cfwdstate(d, l);
                                        ast_safe_sleep(c, 500);
                                        ast_indicate(c, -1);
                                        ast_safe_sleep(c, 1000);
@@ -3357,7 +3767,9 @@ static void *skinny_ss(void *data)
                } else if (res == 0) {
                        ast_debug(1, "Not enough digits (%s) (and no ambiguous match)...\n", d->exten);
                        memset(d->exten, 0, sizeof(d->exten));
-                       transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
+                       if (l->hookstate == SKINNY_OFFHOOK) {
+                               transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
+                       }
                        if (sub->owner && sub->owner->_state != AST_STATE_UP) {
                                ast_indicate(c, -1);
                                ast_hangup(c);
@@ -3367,9 +3779,11 @@ static void *skinny_ss(void *data)
                           ((d->exten[0] != '*') || (!ast_strlen_zero(d->exten) > 2))) {
                        ast_log(LOG_WARNING, "Can't match [%s] from '%s' in context %s\n", d->exten, c->cid.cid_num ? c->cid.cid_num : "<Unknown Caller>", c->context);
                        memset(d->exten, 0, sizeof(d->exten));
-                       transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
-                       /* hang out for 3 seconds to let congestion play */
-                       ast_safe_sleep(c, 3000);
+                       if (l->hookstate == SKINNY_OFFHOOK) {
+                               transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
+                               /* hang out for 3 seconds to let congestion play */
+                               ast_safe_sleep(c, 3000);
+                       }
                        break;
                }
                if (!timeout) {
@@ -3393,8 +3807,7 @@ static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
        int tone = 0;
        struct skinny_subchannel *sub = ast->tech_pvt;
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
+       struct skinny_device *d = l->device;
 
        if (!d->registered) {
                ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
@@ -3414,24 +3827,30 @@ static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
                return -1;
        }
 
+       if (AST_LIST_NEXT(sub,list) && !l->callwaiting) {
+               ast_queue_control(ast, AST_CONTROL_BUSY);
+               return -1;
+       }
+       
        switch (l->hookstate) {
        case SKINNY_OFFHOOK:
                tone = SKINNY_CALLWAITTONE;
                break;
        case SKINNY_ONHOOK:
                tone = SKINNY_ALERT;
+               l->activesub = sub;
                break;
        default:
                ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
                break;
        }
 
-       transmit_callstateonly(s, sub, SKINNY_RINGIN);
-       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGIN);
-       transmit_displaypromptstatus(s, "Ring-In", 0, l->instance, sub->callid);
-       transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
-       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
-       transmit_ringer_mode(s, SKINNY_RING_INSIDE);
+       transmit_callstateonly(d, sub, SKINNY_RINGIN);
+       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGIN);
+       transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
+       transmit_callinfo(d, ast->connected.id.name, ast->connected.id.number, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
+       transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
+       transmit_ringer_mode(d, SKINNY_RING_INSIDE);
 
        ast_setstate(ast, AST_STATE_RINGING);
        ast_queue_control(ast, AST_CONTROL_RINGING);
@@ -3441,7 +3860,7 @@ static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
 
 static int skinny_hangup(struct ast_channel *ast)
 {
-       struct skinny_subchannel *sub = ast->tech_pvt, *tmpsub;
+       struct skinny_subchannel *sub = ast->tech_pvt;
        struct skinny_line *l;
        struct skinny_device *d;
        struct skinnysession *s;
@@ -3450,91 +3869,66 @@ static int skinny_hangup(struct ast_channel *ast)
                ast_debug(1, "Asked to hangup channel not connected\n");
                return 0;
        }
+
        l = sub->parent;
-       d = l->parent;
+       d = l->device;
        s = d->session;
 
-       if (l->sub == sub) {
-               l->sub = l->sub->next;
-       } else {
-               tmpsub = l->sub;
-               while (tmpsub->next) {
-                       if (tmpsub->next == sub) {
-                               tmpsub->next = tmpsub->next->next;
-                               break;
-                       }
-               }
-       }
+       if (skinnydebug)
+               ast_verb(3,"Hanging up %s/%d\n",d->name,sub->callid);
+
+       AST_LIST_REMOVE(&l->sub, sub, list);
 
        if (d->registered) {
                /* Ignoring l->type, doesn't seem relevant and previous code 
                   assigned rather than tested, ie always true */
-               if (l->sub) {
+               if (!AST_LIST_EMPTY(&l->sub)) {
                        if (sub->related) {
                                sub->related->related = NULL;
 
                        }
                        if (sub == l->activesub) {      /* we are killing the active sub, but there are other subs on the line*/
+                               ast_verb(4,"Killing active sub %d\n", sub->callid);
                                if (sub->related) {
                                        l->activesub = sub->related;
                                } else {
-                                       if (sub->next) {
-                                               l->activesub = sub->next;
+                                       if (AST_LIST_NEXT(sub, list)) {
+                                               l->activesub = AST_LIST_NEXT(sub, list);
                                        } else {
-                                               l->activesub = l->sub;
+                                               l->activesub = AST_LIST_FIRST(&l->sub);
                                        }
                                }
-                               transmit_activatecallplane(s, l);
-                               transmit_closereceivechannel(s,sub);
-                               transmit_stopmediatransmission(s,sub);
-                               transmit_tone(s, SKINNY_CALLWAITTONE, l->instance, l->activesub->callid);
-                               transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
+                               //transmit_callstate(d, l->instance, SKINNY_ONHOOK, sub->callid);
+                               transmit_activatecallplane(d, l);
+                               transmit_closereceivechannel(d, sub);
+                               transmit_stopmediatransmission(d, sub);
+                               transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
+                               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                        } else {    /* we are killing a background sub on the line with other subs*/
-                               if (l->sub->next) {
-                                       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
+                               ast_verb(4,"Killing inactive sub %d\n", sub->callid);
+                               if (AST_LIST_NEXT(sub, list)) {
+                                       transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
                                } else {
-                                       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
+                                       transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
                                }
                        }
                } else {                                                /* no more subs on line so make idle */
-
+                       ast_verb(4,"Killing only sub %d\n", sub->callid);
                        l->hookstate = SKINNY_ONHOOK;
-                       transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
+                       transmit_callstate(d, l->instance, SKINNY_ONHOOK, sub->callid);
                        l->activesub = NULL;
-                       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
+                       transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
                        if (sub->parent == d->activeline) {
-                               transmit_activatecallplane(s, l);
-                               transmit_closereceivechannel(s,sub);
-                               transmit_stopmediatransmission(s,sub);
-                               transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
-                               transmit_ringer_mode(s, SKINNY_RING_OFF);
+                               transmit_activatecallplane(d, l);
+                               transmit_closereceivechannel(d, sub);
+                               transmit_stopmediatransmission(d, sub);
+                               transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
+                               transmit_ringer_mode(d, SKINNY_RING_OFF);
+                               transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                                /* we should check to see if we can start the ringer if another line is ringing */
                        }
                }
-
-               /* if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_OFFHOOK)) {
-                       transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
-                       if (onlysub){
-                               if (skinnydebug)
-                                       ast_debug(1, "skinny_hangup(%s) on %s@%s is not the only call on this device\n", ast->name, l->name, d->name);
-                               l->hookstate = SKINNY_ONHOOK;
-                               transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
-                               transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
-                               transmit_ringer_mode(s, SKINNY_RING_OFF);
-                       } else {
-                               transmit_ringer_mode(s, SKINNY_RING_OFF);
-                               if (skinnydebug)
-                                       ast_debug(1, "skinny_hangup(%s) on %s@%s \n", ast->name, l->name, d->name);
-                       }
-                       /ends
-
-               } else if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_ONHOOK)) {
-                       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
-                       transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
-                       transmit_ringer_mode(s, SKINNY_RING_OFF);
-                       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
-                       do_housekeeping(s);
-               } */
        }
        ast_mutex_lock(&sub->lock);
        sub->owner = NULL;
@@ -3542,10 +3936,12 @@ static int skinny_hangup(struct ast_channel *ast)
        sub->alreadygone = 0;
        sub->outgoing = 0;
        if (sub->rtp) {
-               ast_rtp_destroy(sub->rtp);
+               ast_rtp_instance_destroy(sub->rtp);
                sub->rtp = NULL;
        }
        ast_mutex_unlock(&sub->lock);
+       ast_free(sub);
+       ast_module_unref(ast_module_info->self);
        return 0;
 }
 
@@ -3554,11 +3950,7 @@ static int skinny_answer(struct ast_channel *ast)
        int res = 0;
        struct skinny_subchannel *sub = ast->tech_pvt;
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
-       char exten[AST_MAX_EXTENSION] = "";
-
-       ast_copy_string(exten, S_OR(ast->macroexten, ast->exten), sizeof(exten));
+       struct skinny_device *d = l->device;
 
        if (sub->blindxfer) {
                if (skinnydebug)
@@ -3579,15 +3971,15 @@ static int skinny_answer(struct ast_channel *ast)
                ast_setstate(ast, AST_STATE_UP);
        }
 
-       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+       transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
        /* order matters here...
           for some reason, transmit_callinfo must be before transmit_callstate,
           or you won't get keypad messages in some situations. */
-       transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, exten, exten, l->instance, sub->callid, 2);
-       transmit_callstateonly(s, sub, SKINNY_CONNECTED);
-       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
-       transmit_dialednumber(s, exten, l->instance, sub->callid);
-       transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
+       transmit_callinfo(d, ast->connected.id.name, ast->connected.id.number, l->lastnumberdialed, l->lastnumberdialed, l->instance, sub->callid, 2);
+       transmit_callstateonly(d, sub, SKINNY_CONNECTED);
+       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED);
+       transmit_dialednumber(d, l->lastnumberdialed, l->instance, sub->callid);
+       transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
        l->activesub = sub;
        return res;
 }
@@ -3605,16 +3997,16 @@ static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
 
        switch(ast->fdno) {
        case 0:
-               f = ast_rtp_read(sub->rtp); /* RTP Audio */
+               f = ast_rtp_instance_read(sub->rtp, 0); /* RTP Audio */
                break;
        case 1:
-               f = ast_rtcp_read(sub->rtp); /* RTCP Control Channel */
+               f = ast_rtp_instance_read(sub->rtp, 1); /* RTCP Control Channel */
                break;
        case 2:
-               f = ast_rtp_read(sub->vrtp); /* RTP Video */
+               f = ast_rtp_instance_read(sub->vrtp, 0); /* RTP Video */
                break;
        case 3:
-               f = ast_rtcp_read(sub->vrtp); /* RTCP Control Channel for video */
+               f = ast_rtp_instance_read(sub->vrtp, 1); /* RTCP Control Channel for video */
                break;
 #if 0
        case 5:
@@ -3629,9 +4021,9 @@ static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
        if (ast) {
                /* We already hold the channel lock */
                if (f->frametype == AST_FRAME_VOICE) {
-                       if (f->subclass != ast->nativeformats) {
-                               ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
-                               ast->nativeformats = f->subclass;
+                       if (f->subclass.codec != ast->nativeformats) {
+                               ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(f->subclass.codec));
+                               ast->nativeformats = f->subclass.codec;
                                ast_set_read_format(ast, ast->readformat);
                                ast_set_write_format(ast, ast->writeformat);
                        }
@@ -3662,16 +4054,20 @@ static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
                        return 0;
                }
        } else {
-               if (!(frame->subclass & ast->nativeformats)) {
-                       ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
-                               frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
+               if (!(frame->subclass.codec & ast->nativeformats)) {
+                       char buf[256];
+                       ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
+                               ast_getformatname(frame->subclass.codec),
+                               ast_getformatname_multiple(buf, sizeof(buf), ast->nativeformats),
+                               ast_getformatname(ast->readformat),
+                               ast_getformatname(ast->writeformat));
                        return -1;
                }
        }
        if (sub) {
                ast_mutex_lock(&sub->lock);
                if (sub->rtp) {
-                       res = ast_rtp_write(sub->rtp, frame);
+                       res = ast_rtp_instance_write(sub->rtp, frame);
                }
                ast_mutex_unlock(&sub->lock);
        }
@@ -3700,11 +4096,11 @@ static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned in
 #if 0
        struct skinny_subchannel *sub = ast->tech_pvt;
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
+       struct skinny_device *d = l->device;
        int tmp;
        /* not right */
        sprintf(tmp, "%d", digit);
-       transmit_tone(d->session, digit, l->instance, sub->callid);
+       transmit_tone(d, digit, l->instance, sub->callid);
 #endif
        return -1; /* Stop inband indications */
 }
@@ -3716,7 +4112,7 @@ static int get_devicestate(struct skinny_line *l)
 
        if (!l)
                res = AST_DEVICE_INVALID;
-       else if (!l->parent)
+       else if (!l->device)
                res = AST_DEVICE_UNAVAILABLE;
        else if (l->dnd)
                res = AST_DEVICE_BUSY;
@@ -3727,7 +4123,7 @@ static int get_devicestate(struct skinny_line *l)
                        res = AST_DEVICE_INUSE;
                }
 
-               for (sub = l->sub; sub; sub = sub->next) {
+               AST_LIST_TRAVERSE(&l->sub, sub, list) {
                        if (sub->onhold) {
                                res = AST_DEVICE_ONHOLD;
                                break;
@@ -3776,6 +4172,12 @@ static char *control2str(int ind) {
                return "Hold";
        case AST_CONTROL_UNHOLD:
                return "Unhold";
+       case AST_CONTROL_SRCUPDATE:
+               return "Media Source Update";
+       case AST_CONTROL_CONNECTED_LINE:
+               return "Connected Line";
+       case AST_CONTROL_REDIRECTING:
+               return "Redirecting";
        case -1:
                return "Stop tone";
        default:
@@ -3790,7 +4192,7 @@ static int skinny_transfer(struct skinny_subchannel *sub)
 {
        struct skinny_subchannel *xferor; /* the sub doing the transferring */
        struct skinny_subchannel *xferee; /* the sub being transferred */
-       const struct ind_tone_zone_sound *ts = NULL;
+       struct ast_tone_zone_sound *ts = NULL;
                
        if (ast_bridged_channel(sub->owner) || ast_bridged_channel(sub->related->owner)) {
                if (sub->xferor) {
@@ -3813,8 +4215,10 @@ static int skinny_transfer(struct skinny_subchannel *sub)
                        }
                        if (xferor->owner->_state == AST_STATE_RING) {
                                /* play ringing inband */
-                               ts = ast_get_indication_tone(xferor->owner->zone, "ring");
-                               ast_playtones_start(xferor->owner,0,ts->data, 1);
+                               if ((ts = ast_get_indication_tone(xferor->owner->zone, "ring"))) {
+                                       ast_playtones_start(xferor->owner, 0, ts->data, 1);
+                                       ts = ast_tone_zone_sound_unref(ts);
+                               }
                        }
                        if (skinnydebug)
                                ast_debug(1, "Transfer Masquerading %s to %s\n",
@@ -3828,8 +4232,10 @@ static int skinny_transfer(struct skinny_subchannel *sub)
                        ast_queue_control(xferee->owner, AST_CONTROL_UNHOLD);
                        if (xferor->owner->_state == AST_STATE_RING) {
                                /* play ringing inband */
-                               ts = ast_get_indication_tone(xferor->owner->zone, "ring");
-                               ast_playtones_start(xferor->owner,0,ts->data, 1);
+                               if ((ts = ast_get_indication_tone(xferor->owner->zone, "ring"))) {
+                                       ast_playtones_start(xferor->owner, 0, ts->data, 1);
+                                       ts = ast_tone_zone_sound_unref(ts);
+                               }
                        }
                        if (skinnydebug)
                                ast_debug(1, "Transfer Masquerading %s to %s\n",
@@ -3853,17 +4259,14 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
 {
        struct skinny_subchannel *sub = ast->tech_pvt;
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
+       struct skinny_device *d = l->device;
        struct skinnysession *s = d->session;
-       char exten[AST_MAX_EXTENSION] = "";
 
        if (!s) {
                ast_log(LOG_NOTICE, "Asked to indicate '%s' condition on channel %s, but session does not exist.\n", control2str(ind), ast->name);
                return -1;
        }
 
-       ast_copy_string(exten, S_OR(ast->macroexten, ast->exten), sizeof(exten));
-
        if (skinnydebug)
                ast_verb(3, "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
        switch(ind) {
@@ -3877,12 +4280,12 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
                if (ast->_state != AST_STATE_UP) {
                        if (!sub->progress) {
                                if (!d->earlyrtp) {
-                                       transmit_tone(s, SKINNY_ALERT, l->instance, sub->callid);
+                                       transmit_tone(d, SKINNY_ALERT, l->instance, sub->callid);
                                }
-                               transmit_callstateonly(s, sub, SKINNY_RINGOUT);
-                               transmit_dialednumber(s, exten, l->instance, sub->callid);
-                               transmit_displaypromptstatus(s, "Ring Out", 0, l->instance, sub->callid);
-                               transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, exten, exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
+                               transmit_callstateonly(d, sub, SKINNY_RINGOUT);
+                               transmit_dialednumber(d, l->lastnumberdialed, l->instance, sub->callid);
+                               transmit_displaypromptstatus(d, "Ring Out", 0, l->instance, sub->callid);
+                               transmit_callinfo(d, ast->cid.cid_name, ast->cid.cid_num, S_OR(ast->connected.id.name, l->lastnumberdialed), S_OR(ast->connected.id.number, l->lastnumberdialed), l->instance, sub->callid, 2); /* 2 = outgoing from phone */
                                sub->ringing = 1;
                                if (!d->earlyrtp) {
                                        break;
@@ -3893,9 +4296,9 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
        case AST_CONTROL_BUSY:
                if (ast->_state != AST_STATE_UP) {
                        if (!d->earlyrtp) {
-                               transmit_tone(s, SKINNY_BUSYTONE, l->instance, sub->callid);
+                               transmit_tone(d, SKINNY_BUSYTONE, l->instance, sub->callid);
                        }
-                       transmit_callstateonly(s, sub, SKINNY_BUSY);
+                       transmit_callstateonly(d, sub, SKINNY_BUSY);
                        sub->alreadygone = 1;
                        ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
                        if (!d->earlyrtp) {
@@ -3906,9 +4309,9 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
        case AST_CONTROL_CONGESTION:
                if (ast->_state != AST_STATE_UP) {
                        if (!d->earlyrtp) {
-                               transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
+                               transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
                        }
-                       transmit_callstateonly(s, sub, SKINNY_CONGESTION);
+                       transmit_callstateonly(d, sub, SKINNY_CONGESTION);
                        sub->alreadygone = 1;
                        ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
                        if (!d->earlyrtp) {
@@ -3919,11 +4322,11 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
        case AST_CONTROL_PROGRESS:
                if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
                        if (!d->earlyrtp) {
-                               transmit_tone(s, SKINNY_ALERT, l->instance, sub->callid);
+                               transmit_tone(d, SKINNY_ALERT, l->instance, sub->callid);
                        }
-                       transmit_callstateonly(s, sub, SKINNY_PROGRESS);
-                       transmit_displaypromptstatus(s, "Call Progress", 0, l->instance, sub->callid);
-                       transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, exten, exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
+                       transmit_callstateonly(d, sub, SKINNY_PROGRESS);
+                       transmit_displaypromptstatus(d, "Call Progress", 0, l->instance, sub->callid);
+                       transmit_callinfo(d, ast->cid.cid_name, ast->cid.cid_num, S_OR(ast->connected.id.name, l->lastnumberdialed), S_OR(ast->connected.id.number, l->lastnumberdialed), l->instance, sub->callid, 2); /* 2 = outgoing from phone */
                        sub->progress = 1;
                        if (!d->earlyrtp) {
                                break;
@@ -3931,7 +4334,7 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
                }
                return -1; /* Tell asterisk to provide inband signalling */
        case -1:  /* STOP_TONE */
-               transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                break;
        case AST_CONTROL_HOLD:
                ast_moh_start(ast, data, l->mohinterpret);
@@ -3942,9 +4345,10 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
        case AST_CONTROL_PROCEEDING:
                break;
        case AST_CONTROL_SRCUPDATE:
-               if (sub->rtp) {
-                       ast_rtp_new_source(sub->rtp);
-               }
+               ast_rtp_instance_new_source(sub->rtp);
+               break;
+       case AST_CONTROL_CONNECTED_LINE:
+               update_connectedline(sub, data, datalen);
                break;
        default:
                ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
@@ -3953,15 +4357,20 @@ static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, s
        return 0;
 }
 
-static struct ast_channel *skinny_new(struct skinny_line *l, int state)
+static struct ast_channel *skinny_new(struct skinny_line *l, int state, const char *linkedid)
 {
        struct ast_channel *tmp;
        struct skinny_subchannel *sub;
-       struct skinny_device *d = l->parent;
+       struct skinny_device *d = l->device;
        struct ast_variable *v = NULL;
        int fmt;
 
-       tmp = ast_channel_alloc(1, state, l->cid_num, l->cid_name, l->accountcode, l->exten, l->context, l->amaflags, "Skinny/%s@%s-%d", l->name, d->name, callnums);
+       if (!l->device) {
+               ast_log(LOG_WARNING, "Device for line %s is not registered.\n", l->name);
+               return NULL;
+       }
+
+       tmp = ast_channel_alloc(1, state, l->cid_num, l->cid_name, l->accountcode, l->exten, l->context, linkedid, l->amaflags, "Skinny/%s@%s-%d", l->name, d->name, callnums);
        if (!tmp) {
                ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
                return NULL;
@@ -3985,21 +4394,24 @@ static struct ast_channel *skinny_new(struct skinny_line *l, int state)
                        sub->xferor = 0;
                        sub->related = NULL;
 
-
-                       sub->next = l->sub;
-                       l->sub = sub;
-                       l->activesub = sub;
+                       AST_LIST_INSERT_HEAD(&l->sub, sub, list);
+                       //l->activesub = sub;
                }
                tmp->tech = &skinny_tech;
                tmp->tech_pvt = sub;
                tmp->nativeformats = l->capability;
                if (!tmp->nativeformats)
+                       // Should throw an error
                        tmp->nativeformats = default_capability;
                fmt = ast_best_codec(tmp->nativeformats);
-               if (skinnydebug)
-                       ast_verb(1, "skinny_new: tmp->nativeformats=%d fmt=%d\n", tmp->nativeformats, fmt);
+               if (skinnydebug) {
+                       char buf[256];
+                       ast_verb(1, "skinny_new: tmp->nativeformats=%s fmt=%s\n",
+                               ast_getformatname_multiple(buf, sizeof(buf), tmp->nativeformats),
+                               ast_getformatname(fmt));
+               }
                if (sub->rtp) {
-                       ast_channel_set_fd(tmp, 0, ast_rtp_fd(sub->rtp));
+                       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(sub->rtp, 0));
                }
                if (state == AST_STATE_RING) {
                        tmp->rings = 1;
@@ -4012,6 +4424,8 @@ static struct ast_channel *skinny_new(struct skinny_line *l, int state)
                        ast_string_field_set(tmp, language, l->language);
                if (!ast_strlen_zero(l->accountcode))
                        ast_string_field_set(tmp, accountcode, l->accountcode);
+               if (!ast_strlen_zero(l->parkinglot))
+                       ast_string_field_set(tmp, parkinglot, l->parkinglot);
                if (l->amaflags)
                        tmp->amaflags = l->amaflags;
 
@@ -4059,8 +4473,7 @@ static struct ast_channel *skinny_new(struct skinny_line *l, int state)
 static int skinny_hold(struct skinny_subchannel *sub)
 {
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
+       struct skinny_device *d = l->device;
 
        /* Don't try to hold a channel that doesn't exist */
        if (!sub || !sub->owner)
@@ -4074,12 +4487,12 @@ static int skinny_hold(struct skinny_subchannel *sub)
                S_OR(l->mohsuggest, NULL),
                !ast_strlen_zero(l->mohsuggest) ? strlen(l->mohsuggest) + 1 : 0);
 
-       transmit_activatecallplane(s, l);
-       transmit_closereceivechannel(s,sub);
-       transmit_stopmediatransmission(s,sub);
+       transmit_activatecallplane(d, l);
+       transmit_closereceivechannel(d, sub);
+       transmit_stopmediatransmission(d, sub);
 
-       transmit_callstateonly(s, sub, SKINNY_HOLD);
-       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_WINK);
+       transmit_callstateonly(d, sub, SKINNY_HOLD);
+       transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_WINK);
        sub->onhold = 1;
        return 1;
 }
@@ -4087,8 +4500,7 @@ static int skinny_hold(struct skinny_subchannel *sub)
 static int skinny_unhold(struct skinny_subchannel *sub)
 {
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
+       struct skinny_device *d = l->device;
 
        /* Don't try to unhold a channel that doesn't exist */
        if (!sub || !sub->owner)
@@ -4100,11 +4512,11 @@ static int skinny_unhold(struct skinny_subchannel *sub)
 
        ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
 
-       transmit_activatecallplane(s, l);
+       transmit_activatecallplane(d, l);
 
-       transmit_connect(s, sub);
-       transmit_callstateonly(s, sub, SKINNY_CONNECTED);
-       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
+       transmit_connect(d, sub);
+       transmit_callstateonly(d, sub, SKINNY_CONNECTED);
+       transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
        l->hookstate = SKINNY_OFFHOOK;
        sub->onhold = 0;
        return 1;
@@ -4121,10 +4533,10 @@ static int handle_hold_button(struct skinny_subchannel *sub)
        } else {
                if (sub->onhold) {
                        skinny_unhold(sub);
-                       transmit_selectsoftkeys(sub->parent->parent->session, sub->parent->instance, sub->callid, KEYDEF_CONNECTED);
+                       transmit_selectsoftkeys(sub->parent->device, sub->parent->instance, sub->callid, KEYDEF_CONNECTED);
                } else {
                        skinny_hold(sub);
-                       transmit_selectsoftkeys(sub->parent->parent->session, sub->parent->instance, sub->callid, KEYDEF_ONHOLD);
+                       transmit_selectsoftkeys(sub->parent->device, sub->parent->instance, sub->callid, KEYDEF_ONHOLD);
                }
        }
        return 1;
@@ -4133,8 +4545,7 @@ static int handle_hold_button(struct skinny_subchannel *sub)
 static int handle_transfer_button(struct skinny_subchannel *sub)
 {
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
+       struct skinny_device *d = l->device;
        struct skinny_subchannel *newsub;
        struct ast_channel *c;
        pthread_t t;
@@ -4148,7 +4559,7 @@ static int handle_transfer_button(struct skinny_subchannel *sub)
                if (!sub->onhold) {
                        skinny_hold(sub);
                }
-               c = skinny_new(l, AST_STATE_DOWN);
+               c = skinny_new(l, AST_STATE_DOWN, NULL);
                if (c) {
                        newsub = c->tech_pvt;
                        /* point the sub and newsub at each other so we know they are related */
@@ -4156,12 +4567,12 @@ static int handle_transfer_button(struct skinny_subchannel *sub)
                        sub->related = newsub;
                        newsub->xferor = 1;
                        l->activesub = newsub;
-                       transmit_callstate(s, l->instance, SKINNY_OFFHOOK, newsub->callid);
+                       transmit_callstate(d, l->instance, SKINNY_OFFHOOK, newsub->callid);
                        if (skinnydebug)
                                ast_debug(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-                       transmit_displaymessage(s, NULL, l->instance, newsub->callid); /* clear display */
-                       transmit_tone(s, SKINNY_DIALTONE, l->instance, newsub->callid);
-                       transmit_selectsoftkeys(s, l->instance, newsub->callid, KEYDEF_OFFHOOKWITHFEAT);
+                       transmit_displaymessage(d, NULL, l->instance, newsub->callid); /* clear display */
+                       transmit_tone(d, SKINNY_DIALTONE, l->instance, newsub->callid);
+                       transmit_selectsoftkeys(d, l->instance, newsub->callid, KEYDEF_OFFHOOKWITHFEAT);
                        /* start the switch thread */
                        if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
                                ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
@@ -4197,13 +4608,13 @@ static int handle_keep_alive_message(struct skinny_req *req, struct skinnysessio
        if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
                return -1;
 
-       transmit_response(s, req);
-       do_housekeeping(s);
+       transmit_response(s->device, req);
        return 1;
 }
 
 static int handle_register_message(struct skinny_req *req, struct skinnysession *s)
 {
+       struct skinny_device *d = NULL;
        char name[16];
        int res;
 
@@ -4216,11 +4627,34 @@ static int handle_register_message(struct skinny_req *req, struct skinnysession
                        return -1;
 
                snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
-               transmit_response(s, req);
+
+               /* transmit_respons in line as we don't have a valid d */
+               ast_mutex_lock(&s->lock);
+
+               if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
+                       ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
+                       ast_mutex_unlock(&s->lock);
+                       return -1;
+               }
+
+               memset(s->outbuf, 0, sizeof(s->outbuf));
+               memcpy(s->outbuf, req, skinny_header_size);
+               memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
+
+               res = write(s->fd, s->outbuf, letohl(req->len)+8);
+
+               if (res != letohl(req->len)+8) {
+                       ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
+               }
+       
+               ast_mutex_unlock(&s->lock);
+
                return 0;
        }
        ast_verb(3, "Device '%s' successfully registered\n", name);
 
+       d = s->device;
+       
        if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
                return -1;
 
@@ -4231,14 +4665,14 @@ static int handle_register_message(struct skinny_req *req, struct skinnysession
        req->data.regack.res2[0] = '0';
        req->data.regack.res2[1] = '\0';
        req->data.regack.secondaryKeepAlive = htolel(keep_alive);
-       transmit_response(s, req);
+       transmit_response(d, req);
        if (skinnydebug)
                ast_verb(1, "Requesting capabilities\n");
 
        if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
                return -1;
 
-       transmit_response(s, req);
+       transmit_response(d, req);
 
        return res;
 }
@@ -4246,35 +4680,34 @@ static int handle_register_message(struct skinny_req *req, struct skinnysession
 static int handle_callforward_button(struct skinny_subchannel *sub, int cfwdtype)
 {
        struct skinny_line *l = sub->parent;
-       struct skinny_device *d = l->parent;
-       struct skinnysession *s = d->session;
+       struct skinny_device *d = l->device;
        struct ast_channel *c = sub->owner;
        pthread_t t;
 
        if (l->hookstate == SKINNY_ONHOOK) {
                l->hookstate = SKINNY_OFFHOOK;
-               transmit_speaker_mode(s, SKINNY_SPEAKERON);
-               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+               transmit_speaker_mode(d, SKINNY_SPEAKERON);
+               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
        }
        if (skinnydebug)
                ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
+       transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
 
        if (l->cfwdtype & cfwdtype) {
                set_callforwards(l, NULL, cfwdtype);
                ast_safe_sleep(c, 500);
-               transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
-               transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
-               transmit_displaynotify(s, "CFwd disabled", 10);
+               transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
+               transmit_callstate(d, l->instance, SKINNY_ONHOOK, sub->callid);
+               transmit_displaynotify(d, "CFwd disabled", 10);
                if (sub->owner && sub->owner->_state != AST_STATE_UP) {
                        ast_indicate(c, -1);
                        ast_hangup(c);
                }
-               transmit_cfwdstate(s, l);
+               transmit_cfwdstate(d, l);
        } else {
                l->getforward = cfwdtype;
-               transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-               transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
+               transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+               transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUT);
                if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
                        ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
                        ast_hangup(c);
@@ -4321,7 +4754,7 @@ static int handle_keypad_button_message(struct skinny_req *req, struct skinnyses
                ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
        }
 
-       f.subclass = dgt;
+       f.subclass.integer = dgt;
 
        f.src = "skinny";
 
@@ -4344,13 +4777,13 @@ static int handle_keypad_button_message(struct skinny_req *req, struct skinnyses
                f.frametype = AST_FRAME_DTMF_END;
                ast_queue_frame(sub->owner, &f);
                /* XXX This seriously needs to be fixed */
-               if (sub->next && sub->next->owner) {
+               if (AST_LIST_NEXT(sub, list) && AST_LIST_NEXT(sub, list)->owner) {
                        if (sub->owner->_state == 0) {
                                f.frametype = AST_FRAME_DTMF_BEGIN;
-                               ast_queue_frame(sub->next->owner, &f);
+                               ast_queue_frame(AST_LIST_NEXT(sub, list)->owner, &f);
                        }
                        f.frametype = AST_FRAME_DTMF_END;
-                       ast_queue_frame(sub->next->owner, &f);
+                       ast_queue_frame(AST_LIST_NEXT(sub, list)->owner, &f);
                }
        } else {
                if (skinnydebug)
@@ -4386,6 +4819,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                if (!l) {
                        return 0;
                }
+               sub = l->activesub;
        } else {
                l = sub->parent;
        }
@@ -4398,29 +4832,30 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                if (ast_strlen_zero(l->lastnumberdialed)) {
                        ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found.\n");
                        l->hookstate = SKINNY_ONHOOK;
-                       transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
-                       transmit_callstate(s, l->instance, SKINNY_ONHOOK, instance);
+                       transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
+                       transmit_callstate(d, l->instance, SKINNY_ONHOOK, instance);
                        break;
                }
 
-               c = skinny_new(l, AST_STATE_DOWN);
+               c = skinny_new(l, AST_STATE_DOWN, NULL);
                if (!c) {
                        ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
                } else {
                        sub = c->tech_pvt;
                        l = sub->parent;
+                       l->activesub = sub;
                        if (l->hookstate == SKINNY_ONHOOK) {
                                l->hookstate = SKINNY_OFFHOOK;
-                               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+                               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
                        }
                        if (skinnydebug)
                                ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-                       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-                       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
+                       transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                       transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUT);
 
                        if (!ast_ignore_pattern(c->context, l->lastnumberdialed)) {
-                               transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+                               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                        }
                        ast_copy_string(c->exten, l->lastnumberdialed, sizeof(c->exten));
                        if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
@@ -4440,7 +4875,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                }
 
                if (!sub || !sub->owner)
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                else
                        c = sub->owner;
 
@@ -4449,19 +4884,20 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                } else {
                        sub = c->tech_pvt;
                        l = sub->parent;
+                       l->activesub = sub;
                        if (l->hookstate == SKINNY_ONHOOK) {
                                l->hookstate = SKINNY_OFFHOOK;
-                               transmit_speaker_mode(s, SKINNY_SPEAKERON);
-                               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+                               transmit_speaker_mode(d, SKINNY_SPEAKERON);
+                               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
                        }
                        if (skinnydebug)
                                ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-                       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-                       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
+                       transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                       transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUT);
 
                        if (!ast_ignore_pattern(c->context, sd->exten)) {
-                               transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+                               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                        }
                        if (ast_exists_extension(c, c->context, sd->exten, 1, l->cid_num)) {
                                ast_copy_string(c->exten, sd->exten, sizeof(c->exten));
@@ -4487,7 +4923,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                if (l->transfer)
                        handle_transfer_button(sub);
                else
-                       transmit_displaynotify(s, "Transfer disabled", 10);
+                       transmit_displaynotify(d, "Transfer disabled", 10);
                break;
        case STIMULUS_CONFERENCE:
                if (skinnydebug)
@@ -4499,7 +4935,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                        ast_verb(1, "Received Stimulus: Voicemail(%d/%d)\n", instance, callreference);
 
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -4508,25 +4944,26 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                } else {
                        sub = c->tech_pvt;
                        l = sub->parent;
+                       l->activesub = sub;
 
                        if (ast_strlen_zero(l->vmexten))  /* Exit the call if no VM pilot */
                                break;
 
                        if (l->hookstate == SKINNY_ONHOOK){
                                l->hookstate = SKINNY_OFFHOOK;
-                               transmit_speaker_mode(s, SKINNY_SPEAKERON);
-                               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+                               transmit_speaker_mode(d, SKINNY_SPEAKERON);
+                               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
                        }
 
                        if (skinnydebug)
                                ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
 
-                       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-                       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
+                       transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                       transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUT);
 
-                       if (!ast_ignore_pattern(c->context, vmexten)) {
-                               transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+                       if (!ast_ignore_pattern(c->context, l->vmexten)) {
+                               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                        }
 
                        if (ast_exists_extension(c, c->context, l->vmexten, 1, l->cid_num)) {
@@ -4550,14 +4987,14 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
 
                if ((sub && sub->owner) && (sub->owner->_state ==  AST_STATE_UP)){
                        c = sub->owner;
-                       if (!ast_masq_park_call(ast_bridged_channel(c) , c, 0, &extout)) {
+                       if (!ast_masq_park_call(ast_bridged_channel(c), c, 0, &extout)) {
                                snprintf(message, sizeof(message), "Call Parked at: %d", extout);
-                               transmit_displaynotify(s, message, 10);
+                               transmit_displaynotify(d, message, 10);
                        } else {
-                               transmit_displaynotify(s, "Call Park failed", 10);
+                               transmit_displaynotify(d, "Call Park failed", 10);
                        }
                } else {
-                       transmit_displaynotify(s, "Call Park not available", 10);
+                       transmit_displaynotify(d, "Call Park not available", 10);
                }
                }
                break;
@@ -4569,13 +5006,13 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                if (l->dnd != 0){
                        ast_verb(3, "Disabling DND on %s@%s\n", l->name, d->name);
                        l->dnd = 0;
-                       transmit_lamp_indication(s, STIMULUS_DND, 1, SKINNY_LAMP_ON);
-                       transmit_displaynotify(s, "DnD disabled", 10);
+                       transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_ON);
+                       transmit_displaynotify(d, "DnD disabled", 10);
                } else {
                        ast_verb(3, "Enabling DND on %s@%s\n", l->name, d->name);
                        l->dnd = 1;
-                       transmit_lamp_indication(s, STIMULUS_DND, 1, SKINNY_LAMP_OFF);
-                       transmit_displaynotify(s, "DnD enabled", 10);
+                       transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_OFF);
+                       transmit_displaynotify(d, "DnD enabled", 10);
                }
                break;
        case STIMULUS_FORWARDALL:
@@ -4583,7 +5020,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                        ast_verb(1, "Received Stimulus: Forward All(%d/%d)\n", instance, callreference);
 
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -4600,7 +5037,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                        ast_verb(1, "Received Stimulus: Forward Busy (%d/%d)\n", instance, callreference);
 
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -4618,7 +5055,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
 
 #if 0 /* Not sure how to handle this yet */
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -4649,37 +5086,36 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                d->activeline = l;
 
                /* turn the speaker on */
-               transmit_speaker_mode(s, SKINNY_SPEAKERON);
-               transmit_ringer_mode(s, SKINNY_RING_OFF);
-               transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
+               transmit_speaker_mode(d, SKINNY_SPEAKERON);
+               transmit_ringer_mode(d, SKINNY_RING_OFF);
+               transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
 
                l->hookstate = SKINNY_OFFHOOK;
 
-               ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
-
                if (sub && sub->outgoing) {
                        /* We're answering a ringing call */
                        ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
-                       transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
-                       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
-                       transmit_callstateonly(s, sub, SKINNY_CONNECTED);
-                       transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
-                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
+                       transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
+                       transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
+                       transmit_callstateonly(d, sub, SKINNY_CONNECTED);
+                       transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
+                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED);
                        start_rtp(sub);
                        ast_setstate(sub->owner, AST_STATE_UP);
                } else {
                        if (sub && sub->owner) {
                                ast_debug(1, "Current subchannel [%s] already has owner\n", sub->owner->name);
                        } else {
-                               c = skinny_new(l, AST_STATE_DOWN);
+                               c = skinny_new(l, AST_STATE_DOWN, NULL);
                                if (c) {
                                        sub = c->tech_pvt;
-                                       transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+                                       l->activesub = sub;
+                                       transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
                                        if (skinnydebug)
                                                ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-                                       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-                                       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
+                                       transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                                       transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_OFFHOOK);
 
                                        /* start the switch thread */
                                        if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
@@ -4697,7 +5133,7 @@ static int handle_stimulus_message(struct skinny_req *req, struct skinnysession
                        ast_verb(1, "RECEIVED UNKNOWN STIMULUS:  %d(%d/%d)\n", event, instance, callreference);
                break;
        }
-       ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
+       ast_devstate_changed(AST_DEVICE_UNKNOWN, "Skinny/%s@%s", l->name, d->name);
 
        return 1;
 }
@@ -4719,7 +5155,7 @@ static int handle_offhook_message(struct skinny_req *req, struct skinnysession *
           probably move hookstate from line to device, afterall, it's actually
            a device that changes hookstates */
 
-       for (tmp = d->lines; tmp; tmp = tmp->next) {
+       AST_LIST_TRAVERSE(&d->lines, tmp, list) {
                if (tmp->hookstate == SKINNY_OFFHOOK) {
                        ast_verbose(VERBOSE_PREFIX_3 "Got offhook message when device (%s@%s) already offhook\n", tmp->name, d->name);
                        return 0;
@@ -4744,39 +5180,40 @@ static int handle_offhook_message(struct skinny_req *req, struct skinnysession *
                sub = l->activesub;
        }
 
-       transmit_ringer_mode(s, SKINNY_RING_OFF);
+       transmit_ringer_mode(d, SKINNY_RING_OFF);
        l->hookstate = SKINNY_OFFHOOK;
 
-       ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
+       ast_devstate_changed(AST_DEVICE_INUSE, "Skinny/%s@%s", l->name, d->name);
 
        if (sub && sub->onhold) {
                return 1;
        }
 
-       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
+       transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
 
        if (sub && sub->outgoing) {
                /* We're answering a ringing call */
                ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
-               transmit_callstateonly(s, sub, SKINNY_CONNECTED);
-               transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
-               transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
-               transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
+               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
+               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
+               transmit_callstateonly(d, sub, SKINNY_CONNECTED);
+               transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED);
                start_rtp(sub);
                ast_setstate(sub->owner, AST_STATE_UP);
        } else {
                if (sub && sub->owner) {
                        ast_debug(1, "Current sub [%s] already has owner\n", sub->owner->name);
                } else {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                        if (c) {
                                sub = c->tech_pvt;
-                               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+                               l->activesub = sub;
+                               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
                                if (skinnydebug)
                                        ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-                               transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-                               transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                               transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
+                               transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                               transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                               transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_OFFHOOK);
 
                                /* start the switch thread */
                                if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
@@ -4795,7 +5232,7 @@ static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s
 {
        struct skinny_device *d = s->device;
        struct skinny_line *l;
-       struct skinny_subchannel *sub, *tmpsub;
+       struct skinny_subchannel *sub;
        int instance;
        int reference;
        int onlysub = 0;
@@ -4812,6 +5249,9 @@ static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s
        } else {
                l = d->activeline;
                sub = l->activesub;
+               if (!sub) {
+                       return 0;
+               }
        }
 
        if (l->hookstate == SKINNY_ONHOOK) {
@@ -4819,23 +5259,16 @@ static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s
                return 0;
        }
 
-       ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
+       ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
 
        if (sub->onhold) {
                return 0;
        }
 
-       if (!l->sub->next) {
+       if (!AST_LIST_NEXT(sub, list)) {
                onlysub = 1;
        } else {
-               tmpsub = l->sub;
-               while (tmpsub->next){
-                       if ((sub == tmpsub->next) && sub->next) {
-                               tmpsub->next = sub->next;
-                               break;
-                       }
-                       tmpsub = tmpsub->next;
-               }
+               AST_LIST_REMOVE(&l->sub, sub, list);
        }
 
        sub->cxmode = SKINNY_CX_RECVONLY;
@@ -4845,7 +5278,7 @@ static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s
                        ast_debug(1, "Skinny %s@%s-%d went on hook\n", l->name, d->name, reference);
        }
 
-       transmit_callstate(s, l->instance, l->hookstate, sub->callid);
+       transmit_callstate(d, l->instance, l->hookstate, sub->callid);
        if (l->transfer && sub->xferor && sub->owner->_state >= AST_STATE_RING) {
                /* We're allowed to transfer, we have two active calls and
                   we made at least one of the calls.  Let's try and transfer */
@@ -4866,9 +5299,6 @@ static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s
                                l->name, d->name, sub->callid);
                }
        }
-       if ((l->hookstate == SKINNY_ONHOOK) && (sub->next && !sub->next->rtp)) {
-               do_housekeeping(s);
-       }
        return 1;
 }
 
@@ -4877,8 +5307,9 @@ static int handle_capabilities_res_message(struct skinny_req *req, struct skinny
        struct skinny_device *d = s->device;
        struct skinny_line *l;
        uint32_t count = 0;
-       int codecs = 0;
+       format_t codecs = 0;
        int i;
+       char buf[256];
 
        count = letohl(req->data.caps.count);
        if (count > SKINNY_MAX_CAPABILITIES) {
@@ -4887,20 +5318,20 @@ static int handle_capabilities_res_message(struct skinny_req *req, struct skinny
        }
 
        for (i = 0; i < count; i++) {
-               int acodec = 0;
+               format_t acodec = 0;
                int scodec = 0;
                scodec = letohl(req->data.caps.caps[i].codec);
                acodec = codec_skinny2ast(scodec);
                if (skinnydebug)
-                       ast_verb(1, "Adding codec capability '%d (%d)'\n", acodec, scodec);
+                       ast_verb(1, "Adding codec capability '%" PRId64 " (%d)'\n", acodec, scodec);
                codecs |= acodec;
        }
 
-       d->capability &= codecs;
-       ast_verb(0, "Device capability set to '%d'\n", d->capability);
-       for (l = d->lines; l; l = l->next) {
+       d->capability = d->confcapability & codecs;
+       ast_verb(0, "Device capability set to '%s'\n", ast_getformatname_multiple(buf, sizeof(buf), d->capability));
+       AST_LIST_TRAVERSE(&d->lines, l, list) {
                ast_mutex_lock(&l->lock);
-               l->capability = d->capability;
+               l->capability = l->confcapability & d->capability;
                ast_mutex_unlock(&l->lock);
        }
 
@@ -4928,7 +5359,7 @@ static int handle_speed_dial_stat_req_message(struct skinny_req *req, struct ski
        ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
        ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
 
-       transmit_response(s, req);
+       transmit_response(d, req);
        return 1;
 }
 
@@ -4941,7 +5372,7 @@ static int handle_line_state_req_message(struct skinny_req *req, struct skinnyse
 
        instance = letohl(req->data.line.lineNumber);
 
-       ast_mutex_lock(&devicelock);
+       AST_LIST_LOCK(&devices);
 
        l = find_line_by_instance(d, instance);
 
@@ -4953,7 +5384,7 @@ static int handle_line_state_req_message(struct skinny_req *req, struct skinnyse
                return 0;
        }
 
-       ast_mutex_unlock(&devicelock);
+       AST_LIST_UNLOCK(&devices);
 
        if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
                return -1;
@@ -4966,19 +5397,19 @@ static int handle_line_state_req_message(struct skinny_req *req, struct skinnyse
                memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
                memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
        }
-       transmit_response(s,req);
+       transmit_response(d, req);
        return 1;
 }
 
 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s)
 {
-       struct timeval tv = ast_tvnow();
+       struct timeval now = ast_tvnow();
        struct ast_tm cmtime;
 
        if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
                return -1;
 
-       ast_localtime(&tv, &cmtime, NULL);
+       ast_localtime(&now, &cmtime, NULL);
        req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
        req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
        req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
@@ -4987,8 +5418,8 @@ static int handle_time_date_req_message(struct skinny_req *req, struct skinnyses
        req->data.definetimedate.minute = htolel(cmtime.tm_min);
        req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
        req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
-       req->data.definetimedate.timestamp = htolel(tv.tv_sec);
-       transmit_response(s, req);
+       req->data.definetimedate.timestamp = htolel(now.tv_sec);
+       transmit_response(s->device, req);
        return 1;
 }
 
@@ -5019,7 +5450,7 @@ static int handle_button_template_req_message(struct skinny_req *req, struct ski
                                req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
                                req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
 
-                               for (l = d->lines; l; l = l->next) {
+                               AST_LIST_TRAVERSE(&d->lines, l, list) {
                                        if (l->instance == lineInstance) {
                                                ast_verb(0, "Adding button: %d, %d\n", BT_LINE, lineInstance);
                                                req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
@@ -5032,7 +5463,7 @@ static int handle_button_template_req_message(struct skinny_req *req, struct ski
                                }
 
                                if (!btnSet) {
-                                       for (sd = d->speeddials; sd; sd = sd->next) {
+                                       AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
                                                if (sd->isHint && sd->instance == lineInstance) {
                                                        ast_verb(0, "Adding button: %d, %d\n", BT_LINE, lineInstance);
                                                        req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
@@ -5050,7 +5481,7 @@ static int handle_button_template_req_message(struct skinny_req *req, struct ski
                                req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
                                req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
 
-                               for (l = d->lines; l; l = l->next) {
+                               AST_LIST_TRAVERSE(&d->lines, l, list) {
                                        if (l->instance == lineInstance) {
                                                ast_verb(0, "Adding button: %d, %d\n", BT_LINE, lineInstance);
                                                req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
@@ -5063,7 +5494,7 @@ static int handle_button_template_req_message(struct skinny_req *req, struct ski
                                }
 
                                if (!btnSet) {
-                                       for (sd = d->speeddials; sd; sd = sd->next) {
+                                       AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
                                                if (sd->isHint && sd->instance == lineInstance) {
                                                        ast_verb(0, "Adding button: %d, %d\n", BT_LINE, lineInstance);
                                                        req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
@@ -5088,7 +5519,7 @@ static int handle_button_template_req_message(struct skinny_req *req, struct ski
                                req->data.buttontemplate.definition[i].buttonDefinition = htolel(BT_NONE);
                                req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
 
-                               for (l = d->lines; l; l = l->next) {
+                               AST_LIST_TRAVERSE(&d->lines, l, list) {
                                        if (l->instance == lineInstance) {
                                                ast_verb(0, "Adding button: %d, %d\n", BT_LINE, lineInstance);
                                                req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
@@ -5104,7 +5535,7 @@ static int handle_button_template_req_message(struct skinny_req *req, struct ski
                                req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
                                req->data.buttontemplate.definition[i].instanceNumber = 0;
 
-                               for (sd = d->speeddials; sd; sd = sd->next) {
+                               AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
                                        if (!sd->isHint && sd->instance == speeddialInstance) {
                                                ast_verb(0, "Adding button: %d, %d\n", BT_SPEEDDIAL, speeddialInstance);
                                                req->data.buttontemplate.definition[i].buttonDefinition = BT_SPEEDDIAL;
@@ -5136,7 +5567,7 @@ static int handle_button_template_req_message(struct skinny_req *req, struct ski
                ast_verb(1, "Sending %d template to %s\n",
                                        d->type,
                                        d->name);
-       transmit_response(s, req);
+       transmit_response(d, req);
        return 1;
 }
 
@@ -5147,7 +5578,7 @@ static int handle_version_req_message(struct skinny_req *req, struct skinnysessi
                return -1;
 
        ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
-       transmit_response(s, req);
+       transmit_response(d, req);
        return 1;
 }
 
@@ -5161,7 +5592,7 @@ static int handle_server_request_message(struct skinny_req *req, struct skinnyse
                        sizeof(req->data.serverres.server[0].serverName));
        req->data.serverres.serverListenPort[0] = htolel(ourport);
        req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
-       transmit_response(s, req);
+       transmit_response(d, req);
        return 1;
 }
 
@@ -5180,8 +5611,8 @@ static int handle_open_receive_channel_ack_message(struct skinny_req *req, struc
        struct skinny_line *l;
        struct skinny_subchannel *sub;
        struct ast_format_list fmt;
-       struct sockaddr_in sin;
-       struct sockaddr_in us;
+       struct sockaddr_in sin = { 0, };
+       struct sockaddr_in us = { 0, };
        uint32_t addr;
        int port;
        int status;
@@ -5208,8 +5639,8 @@ static int handle_open_receive_channel_ack_message(struct skinny_req *req, struc
        l = sub->parent;
 
        if (sub->rtp) {
-               ast_rtp_set_peer(sub->rtp, &sin);
-               ast_rtp_get_us(sub->rtp, &us);
+               ast_rtp_instance_set_remote_address(sub->rtp, &sin);
+               ast_rtp_instance_get_local_address(sub->rtp, &us);
        } else {
                ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
                return 0;
@@ -5224,7 +5655,7 @@ static int handle_open_receive_channel_ack_message(struct skinny_req *req, struc
        fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
 
        if (skinnydebug)
-               ast_verb(1, "Setting payloadType to '%d' (%d ms)\n", fmt.bits, fmt.cur_ms);
+               ast_verb(1, "Setting payloadType to '%s' (%d ms)\n", ast_getformatname(fmt.bits), fmt.cur_ms);
 
        req->data.startmedia.conferenceId = htolel(sub->callid);
        req->data.startmedia.passThruPartyId = htolel(sub->callid);
@@ -5236,7 +5667,7 @@ static int handle_open_receive_channel_ack_message(struct skinny_req *req, struc
        req->data.startmedia.qualifier.vad = htolel(0);
        req->data.startmedia.qualifier.packets = htolel(0);
        req->data.startmedia.qualifier.bitRate = htolel(0);
-       transmit_response(s, req);
+       transmit_response(d, req);
 
        return 1;
 }
@@ -5263,7 +5694,7 @@ static int handle_enbloc_call_message(struct skinny_req *req, struct skinnysessi
                l = sub->parent;
        }
 
-       c = skinny_new(l, AST_STATE_DOWN);
+       c = skinny_new(l, AST_STATE_DOWN, NULL);
 
        if(!c) {
                ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
@@ -5271,14 +5702,15 @@ static int handle_enbloc_call_message(struct skinny_req *req, struct skinnysessi
                l->hookstate = SKINNY_OFFHOOK;
 
                sub = c->tech_pvt;
-               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+               l->activesub = sub;
+               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
                if (skinnydebug)
                        ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-               transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-               transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
+               transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+               transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
 
                if (!ast_ignore_pattern(c->context, req->data.enbloccallmessage.calledParty)) {
-                       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+                       transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                }
                ast_copy_string(c->exten, req->data.enbloccallmessage.calledParty, sizeof(c->exten));
                if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
@@ -5297,6 +5729,7 @@ static int handle_soft_key_set_req_message(struct skinny_req *req, struct skinny
        int x;
        int y;
        const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
+       struct skinny_device *d = s->device;
 
        if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
                return -1;
@@ -5318,8 +5751,8 @@ static int handle_soft_key_set_req_message(struct skinny_req *req, struct skinny
                }
                softkeymode++;
        }
-       transmit_response(s,req);
-       transmit_selectsoftkeys(s, 0, 0, KEYDEF_ONHOOK);
+       transmit_response(d, req);
+       transmit_selectsoftkeys(d, 0, 0, KEYDEF_ONHOOK);
        return 1;
 }
 
@@ -5355,7 +5788,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                return 0;
        }
 
-       ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
+       ast_devstate_changed(AST_DEVICE_INUSE, "Skinny/%s@%s", l->name, d->name);
 
        switch(event) {
        case SOFTKEY_NONE:
@@ -5369,13 +5802,13 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                if (ast_strlen_zero(l->lastnumberdialed)) {
                        ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found.\n");
                        l->hookstate = SKINNY_ONHOOK;
-                       transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
-                       transmit_callstate(s, l->instance, SKINNY_ONHOOK, instance);
+                       transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
+                       transmit_callstate(d, l->instance, SKINNY_ONHOOK, instance);
                        break;
                }
 
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -5384,19 +5817,20 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
                } else {
                        sub = c->tech_pvt;
+                       l->activesub = sub;
                        if (l->hookstate == SKINNY_ONHOOK) {
                                l->hookstate = SKINNY_OFFHOOK;
-                               transmit_speaker_mode(s, SKINNY_SPEAKERON);
-                               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+                               transmit_speaker_mode(d, SKINNY_SPEAKERON);
+                               transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
                        }
                        if (skinnydebug)
                                ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-                       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-                       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
+                       transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                       transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUT);
 
                        if (!ast_ignore_pattern(c->context, l->lastnumberdialed)) {
-                               transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
+                               transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
                        }
                        ast_copy_string(c->exten, l->lastnumberdialed, sizeof(c->exten));
                        if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
@@ -5409,14 +5843,12 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                if (skinnydebug)
                        ast_verb(1, "Received Softkey Event: New Call(%d/%d)\n", instance, callreference);
 
-               if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
-               } else {
-                       c = sub->owner;
-               }
-
-               /* transmit_ringer_mode(s,SKINNY_RING_OFF);
-               transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON); */
+               /* New Call ALWAYS gets a new sub-channel */
+               c = skinny_new(l, AST_STATE_DOWN, NULL);
+               sub = c->tech_pvt;
+       
+               /* transmit_ringer_mode(d, SKINNY_RING_OFF);
+               transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON); */
 
                /* l->hookstate = SKINNY_OFFHOOK; */
 
@@ -5424,17 +5856,20 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
                } else {
                        sub = c->tech_pvt;
+                       l->activesub = sub;
                        if (l->hookstate == SKINNY_ONHOOK) {
                                l->hookstate = SKINNY_OFFHOOK;
-                               transmit_speaker_mode(s, SKINNY_SPEAKERON);
-                               transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
+                               transmit_speaker_mode(d, SKINNY_SPEAKERON);
                        }
+                       ast_verb(1, "Call-id: %d\n", sub->callid);
+
+                       transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
 
                        if (skinnydebug)
                                ast_verb(1, "Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
-                       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
-                       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
-                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
+                       transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
+                       transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
+                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_OFFHOOK);
 
                        /* start the switch thread */
                        if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
@@ -5454,7 +5889,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                if (l->transfer)
                        handle_transfer_button(sub);
                else
-                       transmit_displaynotify(s, "Transfer disabled", 10);
+                       transmit_displaynotify(d, "Transfer disabled", 10);
 
                break;
        case SOFTKEY_DND:
@@ -5465,13 +5900,13 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                if (l->dnd != 0){
                        ast_verb(3, "Disabling DND on %s@%s\n", l->name, d->name);
                        l->dnd = 0;
-                       transmit_lamp_indication(s, STIMULUS_DND, 1, SKINNY_LAMP_ON);
-                       transmit_displaynotify(s, "DnD disabled", 10);
+                       transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_ON);
+                       transmit_displaynotify(d, "DnD disabled", 10);
                } else {
                        ast_verb(3, "Enabling DND on %s@%s\n", l->name, d->name);
                        l->dnd = 1;
-                       transmit_lamp_indication(s, STIMULUS_DND, 1, SKINNY_LAMP_OFF);
-                       transmit_displaynotify(s, "DnD enabled", 10);
+                       transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_OFF);
+                       transmit_displaynotify(d, "DnD enabled", 10);
                }
                break;
        case SOFTKEY_CFWDALL:
@@ -5479,7 +5914,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_verb(1, "Received Softkey Event: Forward All(%d/%d)\n", instance, callreference);
 
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -5488,6 +5923,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
                } else {
                        sub = c->tech_pvt;
+                       l->activesub = sub;
                        handle_callforward_button(sub, SKINNY_CFWD_ALL);
                }
                break;
@@ -5496,7 +5932,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_verb(1, "Received Softkey Event: Forward Busy (%d/%d)\n", instance, callreference);
 
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -5505,6 +5941,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
                } else {
                        sub = c->tech_pvt;
+                       l->activesub = sub;
                        handle_callforward_button(sub, SKINNY_CFWD_BUSY);
                }
                break;
@@ -5514,7 +5951,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
 
 #if 0 /* Not sure how to handle this yet */
                if (!sub || !sub->owner) {
-                       c = skinny_new(l, AST_STATE_DOWN);
+                       c = skinny_new(l, AST_STATE_DOWN, NULL);
                } else {
                        c = sub->owner;
                }
@@ -5523,6 +5960,7 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
                } else {
                        sub = c->tech_pvt;
+                       l->activesub = sub;
                        handle_callforward_button(sub, SKINNY_CFWD_NOANSWER);
                }
 #endif
@@ -5541,19 +5979,11 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                }
                if (sub) {
                        int onlysub = 0;
-                       struct skinny_subchannel *tmpsub;
 
-                       if (!l->sub->next) {
+                       if (!AST_LIST_NEXT(sub, list)) {
                                onlysub = 1;
                        } else {
-                               tmpsub = l->sub;
-                               while (tmpsub->next){
-                                       if ((sub == tmpsub->next) && sub->next) {
-                                               tmpsub->next = sub->next;
-                                               break;
-                                       }
-                                       tmpsub = tmpsub->next;
-                               }
+                               AST_LIST_REMOVE(&l->sub, sub, list);
                        }
 
                        sub->cxmode = SKINNY_CX_RECVONLY;
@@ -5563,7 +5993,8 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                                        ast_debug(1, "Skinny %s@%s-%d went on hook\n", l->name, d->name, callreference);
                        }
 
-                       transmit_callstate(s, l->instance, l->hookstate, sub->callid);
+                       transmit_callstate(d, l->instance, l->hookstate, sub->callid);
+                       ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
                        if (skinnydebug)
                                ast_verb(1, "Skinny %s@%s went on hook\n", l->name, d->name);
                        if (l->transfer && sub->xferor && sub->owner->_state >= AST_STATE_RING) {
@@ -5586,8 +6017,8 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                                                l->name, d->name, sub->callid);
                                }
                        }
-                       if ((l->hookstate == SKINNY_ONHOOK) && (sub->next && !sub->next->rtp)) {
-                               do_housekeeping(s);
+                       if ((l->hookstate == SKINNY_ONHOOK) && (AST_LIST_NEXT(sub, list) && !AST_LIST_NEXT(sub, list)->rtp)) {
+                               ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
                        }
                }
                break;
@@ -5598,10 +6029,10 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                if (sub) {
                        if (sub->onhold) {
                                skinny_unhold(sub);
-                               transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
+                               transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED);
                        } else {
                                skinny_hold(sub);
-                               transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_ONHOLD);
+                               transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_ONHOLD);
                        }
                }
 
@@ -5610,18 +6041,20 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                if (skinnydebug)
                        ast_verb(1, "Received Softkey Event: Answer(%d/%d)\n", instance, callreference);
 
-               transmit_ringer_mode(s,SKINNY_RING_OFF);
-               transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
-
-               l->hookstate = SKINNY_OFFHOOK;
+               transmit_ringer_mode(d, SKINNY_RING_OFF);
+               transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
+               if (l->hookstate == SKINNY_ONHOOK) {
+                       transmit_speaker_mode(d, SKINNY_SPEAKERON);
+                       l->hookstate = SKINNY_OFFHOOK;
+               }
 
                if (sub && sub->outgoing) {
                        /* We're answering a ringing call */
                        ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
-                       transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
-                       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
-                       transmit_callstateonly(s, sub, SKINNY_CONNECTED);
-                       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
+                       transmit_callstate(d, l->instance, SKINNY_OFFHOOK, sub->callid);
+                       transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
+                       transmit_callstateonly(d, sub, SKINNY_CONNECTED);
+                       transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED);
                        start_rtp(sub);
                        ast_setstate(sub->owner, AST_STATE_UP);
                }
@@ -5645,14 +6078,14 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
 
                if ((sub && sub->owner) && (sub->owner->_state ==  AST_STATE_UP)){
                        c = sub->owner;
-                       if (!ast_masq_park_call(ast_bridged_channel(c) , c, 0, &extout)) {
+                       if (!ast_masq_park_call(ast_bridged_channel(c), c, 0, &extout)) {
                                snprintf(message, sizeof(message), "Call Parked at: %d", extout);
-                               transmit_displaynotify(s, message, 10);
+                               transmit_displaynotify(d, message, 10);
                        } else {
-                               transmit_displaynotify(s, "Call Park failed", 10);
+                               transmit_displaynotify(d, "Call Park failed", 10);
                        }
                } else {
-                       transmit_displaynotify(s, "Call Park not available", 10);
+                       transmit_displaynotify(d, "Call Park not available", 10);
                }
                }
                break;
@@ -5678,7 +6111,6 @@ static int handle_soft_key_event_message(struct skinny_req *req, struct skinnyse
                        ast_verb(1, "Received unknown Softkey Event: %d(%d/%d)\n", event, instance, callreference);
                break;
        }
-       ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
 
        return 1;
 }
@@ -5699,7 +6131,7 @@ static int handle_soft_key_template_req_message(struct skinny_req *req, struct s
        memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
                soft_key_template_default,
                sizeof(soft_key_template_default));
-       transmit_response(s,req);
+       transmit_response(s->device, req);
        return 1;
 }
 
@@ -5725,6 +6157,10 @@ static int handle_message(struct skinny_req *req, struct skinnysession *s)
                return 0;
        }
 
+       SKINNY_DEVONLY(if (skinnydebug > 1) {
+               ast_verb(4, "Received %s from %s\n", message2str(req->e), s->device->name);
+       })
+
        switch(letohl(req->e)) {
        case KEEP_ALIVE_MESSAGE:
                res = handle_keep_alive_message(req, s);
@@ -5886,43 +6322,36 @@ static int handle_message(struct skinny_req *req, struct skinnysession *s)
 
 static void destroy_session(struct skinnysession *s)
 {
-       struct skinnysession *cur, *prev = NULL;
-       ast_mutex_lock(&sessionlock);
-       cur = sessions;
-       while(cur) {
+       struct skinnysession *cur;
+       AST_LIST_LOCK(&sessions);
+       AST_LIST_TRAVERSE_SAFE_BEGIN(&sessions, cur, list) {
                if (cur == s) {
-                       break;
-               }
-               prev = cur;
-               cur = cur->next;
-       }
-       if (cur) {
-               if (prev) {
-                       prev->next = cur->next;
+                       AST_LIST_REMOVE_CURRENT(list);
+                       if (s->fd > -1) 
+                               close(s->fd);
+                       
+                       ast_mutex_destroy(&s->lock);
+                       
+                       ast_free(s);
                } else {
-                       sessions = cur->next;
-               }
-               if (s->fd > -1) {
-                       close(s->fd);
+                       ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
                }
-               ast_mutex_destroy(&s->lock);
-               ast_free(s);
-       } else {
-               ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
        }
-       ast_mutex_unlock(&sessionlock);
+       AST_LIST_TRAVERSE_SAFE_END
+       AST_LIST_UNLOCK(&sessions);
 }
 
 static int get_input(struct skinnysession *s)
 {
        int res;
        int dlen = 0;
+       int *bufaddr;
        struct pollfd fds[1];
 
        fds[0].fd = s->fd;
        fds[0].events = POLLIN;
        fds[0].revents = 0;
-       res = poll(fds, 1, (keep_alive * 1100)); /* If nothing has happen, client is dead */
+       res = ast_poll(fds, 1, (keep_alive * 1100)); /* If nothing has happen, client is dead */
                                                 /* we add 10% to the keep_alive to deal */
                                                 /* with network delays, etc */
        if (res < 0) {
@@ -5939,7 +6368,7 @@ static int get_input(struct skinnysession *s)
                     
        if (fds[0].revents) {
                ast_mutex_lock(&s->lock);
-               memset(s->inbuf,0,sizeof(s->inbuf));
+               memset(s->inbuf, 0, sizeof(s->inbuf));
                res = read(s->fd, s->inbuf, 4);
                if (res < 0) {
                        ast_log(LOG_WARNING, "read() returned error: %s\n", strerror(errno));
@@ -5947,7 +6376,7 @@ static int get_input(struct skinnysession *s)
                        if (skinnydebug)
                                ast_verb(1, "Skinny Client was lost, unregistering\n");
 
-                       skinny_unregister(NULL,s);
+                       skinny_unregister(NULL, s);
                        ast_mutex_unlock(&s->lock);
                        return res;
                } else if (res != 4) {
@@ -5963,7 +6392,8 @@ static int get_input(struct skinnysession *s)
                        return -1;
                }
 
-               dlen = letohl(*(int *)s->inbuf);
+               bufaddr = (int *)s->inbuf;
+               dlen = letohl(*bufaddr);
                if (dlen < 4) {
                        ast_debug(1, "Skinny Client sent invalid data.\n");
                        ast_mutex_unlock(&s->lock);
@@ -5972,7 +6402,7 @@ static int get_input(struct skinnysession *s)
                if (dlen+8 > sizeof(s->inbuf)) {
                        dlen = sizeof(s->inbuf) - 8;
                }
-               *(int *)s->inbuf = htolel(dlen);
+               *bufaddr = htolel(dlen);
 
                res = read(s->fd, s->inbuf+4, dlen+4);
                ast_mutex_unlock(&s->lock);
@@ -5991,13 +6421,15 @@ static int get_input(struct skinnysession *s)
 static struct skinny_req *skinny_req_parse(struct skinnysession *s)
 {
        struct skinny_req *req;
+       int *bufaddr;
 
        if (!(req = ast_calloc(1, SKINNY_MAX_PACKET)))
                return NULL;
 
        ast_mutex_lock(&s->lock);
        memcpy(req, s->inbuf, skinny_header_size);
-       memcpy(&req->data, s->inbuf+skinny_header_size, letohl(*(int*)(s->inbuf))-4);
+       bufaddr = (int *)(s->inbuf);
+       memcpy(&req->data, s->inbuf+skinny_header_size, letohl(*bufaddr)-4);
 
        ast_mutex_unlock(&s->lock);
 
@@ -6054,7 +6486,6 @@ static void *accept_thread(void *ignore)
        struct skinnysession *s;
        struct protoent *p;
        int arg = 1;
-       pthread_t tcp_thread;
 
        for (;;) {
                sinlen = sizeof(sin);
@@ -6075,12 +6506,11 @@ static void *accept_thread(void *ignore)
                memcpy(&s->sin, &sin, sizeof(sin));
                ast_mutex_init(&s->lock);
                s->fd = as;
-               ast_mutex_lock(&sessionlock);
-               s->next = sessions;
-               sessions = s;
-               ast_mutex_unlock(&sessionlock);
+               AST_LIST_LOCK(&sessions);
+               AST_LIST_INSERT_HEAD(&sessions, s, list);
+               AST_LIST_UNLOCK(&sessions);
 
-               if (ast_pthread_create_detached(&tcp_thread, NULL, skinny_session, s)) {
+               if (ast_pthread_create(&s->t, NULL, skinny_session, s)) {
                        destroy_session(s);
                }
        }
@@ -6155,9 +6585,9 @@ static int skinny_devicestate(void *data)
        return get_devicestate(l);
 }
 
-static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause)
+static struct ast_channel *skinny_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
 {
-       int oldformat;
+       format_t oldformat;
        
        struct skinny_line *l;
        struct ast_channel *tmpc = NULL;
@@ -6167,7 +6597,7 @@ static struct ast_channel *skinny_request(const char *type, int format, void *da
        oldformat = format;
        
        if (!(format &= AST_FORMAT_AUDIO_MASK)) {
-               ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
+               ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%s'\n", ast_getformatname_multiple(tmp, sizeof(tmp), format));
                return NULL;
        }
 
@@ -6182,7 +6612,7 @@ static struct ast_channel *skinny_request(const char *type, int format, void *da
                return NULL;
        }
        ast_verb(3, "skinny_request(%s)\n", tmp);
-       tmpc = skinny_new(l, AST_STATE_DOWN);
+       tmpc = skinny_new(l, AST_STATE_DOWN, requestor ? requestor->linkedid : NULL);
        if (!tmpc) {
                ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
        }
@@ -6190,103 +6620,565 @@ static struct ast_channel *skinny_request(const char *type, int format, void *da
        return tmpc;
 }
 
-static int reload_config(void)
-{
-       int on = 1;
-       struct ast_config *cfg;
-       struct ast_variable *v;
-       char *cat;
-       struct skinny_device *d;
-       int oldport = ntohs(bindaddr.sin_port);
-       char *stringp, *context, *oldregcontext;
-       char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
-       struct ast_flags config_flags = { 0 };
-
-       if (gethostname(ourhost, sizeof(ourhost))) {
-               ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled\n");
-               return 0;
+ #define TYPE_GENERAL  1
+ #define TYPE_DEF_DEVICE 2
+ #define TYPE_DEF_LINE         4
+ #define TYPE_DEVICE   8
+ #define TYPE_LINE     16
+ #define CLINE_OPTS    ((struct skinny_line_options *)item)
+ #define CLINE         ((struct skinny_line *)item)
+ #define CDEV_OPTS     ((struct skinny_device_options *)item)
+ #define CDEV          ((struct skinny_device *)item)
+ static void config_parse_variables(int type, void *item, struct ast_variable *vptr)
+ {
+       struct ast_variable *v;
+       int lineInstance = 1;
+       int speeddialInstance = 1;
+       
+       while(vptr) {
+               v = vptr;
+               vptr = vptr->next;
+               if (type & (TYPE_GENERAL)) {
+                       char newcontexts[AST_MAX_CONTEXT];
+                       char oldcontexts[AST_MAX_CONTEXT];
+                       char *stringp, *context, *oldregcontext;
+                       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
+                               v = v->next;
+                               continue;
+                       }
+                       if (!strcasecmp(v->name, "bindaddr")) {
+                               if (!(hp = ast_gethostbyname(v->value, &ahp))) {
+                                       ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
+                               } else {
+                                       memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
+                               }
+                               continue;
+                       } else if (!strcasecmp(v->name, "keepalive")) {
+                               keep_alive = atoi(v->value);
+                               continue;
+                       } else if (!strcasecmp(v->name, "regcontext")) {
+                               ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
+                               stringp = newcontexts;
+                               /* Initialize copy of current global_regcontext for later use in removing stale contexts */
+                               ast_copy_string(oldcontexts, regcontext, sizeof(oldcontexts));
+                               oldregcontext = oldcontexts;
+                               /* Let's remove any contexts that are no longer defined in regcontext */
+                               cleanup_stale_contexts(stringp, oldregcontext);
+                               /* Create contexts if they don't exist already */
+                               while ((context = strsep(&stringp, "&"))) {
+                                       ast_copy_string(used_context, context, sizeof(used_context));
+                                       ast_context_find_or_create(NULL, NULL, context, "Skinny");
+                               }
+                               ast_copy_string(regcontext, v->value, sizeof(regcontext));
+                               continue;
+                       } else if (!strcasecmp(v->name, "dateformat")) {
+                               memcpy(date_format, v->value, sizeof(date_format));
+                               continue;
+                       } else if (!strcasecmp(v->name, "tos")) {
+                               if (ast_str2tos(v->value, &qos.tos))
+                                       ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
+                               continue;
+                       } else if (!strcasecmp(v->name, "tos_audio")) {
+                               if (ast_str2tos(v->value, &qos.tos_audio))
+                                       ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
+                               continue;
+                       } else if (!strcasecmp(v->name, "tos_video")) {
+                               if (ast_str2tos(v->value, &qos.tos_video))
+                                       ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
+                               continue;
+                       } else if (!strcasecmp(v->name, "cos")) {
+                               if (ast_str2cos(v->value, &qos.cos))
+                                       ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
+                               continue;
+                       } else if (!strcasecmp(v->name, "cos_audio")) {
+                               if (ast_str2cos(v->value, &qos.cos_audio))
+                                       ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
+                               continue;
+                       } else if (!strcasecmp(v->name, "cos_video")) {
+                               if (ast_str2cos(v->value, &qos.cos_video))
+                                       ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
+                               continue;
+                       } else if (!strcasecmp(v->name, "bindport")) {
+                               if (sscanf(v->value, "%5d", &ourport) == 1) {
+                                       bindaddr.sin_port = htons(ourport);
+                               } else {
+                                       ast_log(LOG_WARNING, "Invalid bindport '%s' at line %d of %s\n", v->value, v->lineno, config);
+                               }
+                               continue;
+                       } else if (!strcasecmp(v->name, "allow")) {
+                               ast_parse_allow_disallow(&default_prefs, &default_capability, v->value, 1);
+                               continue;
+                       } else if (!strcasecmp(v->name, "disallow")) {
+                               ast_parse_allow_disallow(&default_prefs, &default_capability, v->value, 0);
+                               continue;
+                       } 
+               }
+               if (!strcasecmp(v->name, "transfer")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               CDEV_OPTS->transfer = ast_true(v->value);
+                               continue;
+                       } else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->transfer = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "callwaiting")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               CDEV_OPTS->callwaiting = ast_true(v->value);
+                               continue;
+                       } else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->callwaiting = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->directmedia = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "nat")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->nat = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "context")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->context, v->value, sizeof(CLINE_OPTS->context));
+                               continue;
+                       }
+               }else if (!strcasecmp(v->name, "vmexten")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               ast_copy_string(CDEV_OPTS->vmexten, v->value, sizeof(CDEV_OPTS->vmexten));
+                               continue;
+                       } else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->vmexten, v->value, sizeof(CLINE_OPTS->vmexten));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "mwiblink")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               CDEV_OPTS->mwiblink = ast_true(v->value);
+                               continue;
+                       } else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->mwiblink = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "linelabel")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->label, v->value, sizeof(CLINE_OPTS->label));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "callerid")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               if (!strcasecmp(v->value, "asreceived")) {
+                                       CLINE_OPTS->cid_num[0] = '\0';
+                                       CLINE_OPTS->cid_name[0] = '\0';
+                               } else {
+                                       ast_callerid_split(v->value, CLINE_OPTS->cid_name, sizeof(CLINE_OPTS->cid_name), CLINE_OPTS->cid_num, sizeof(CLINE_OPTS->cid_num));
+                               }
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "amaflags")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               int tempamaflags = ast_cdr_amaflags2int(v->value);
+                               if (tempamaflags < 0) {
+                                       ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
+                               } else {
+                                       CLINE_OPTS->amaflags = tempamaflags;
+                               }
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "regexten")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->regexten, v->value, sizeof(CLINE_OPTS->regexten));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "language")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->language, v->value, sizeof(CLINE_OPTS->language));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "accountcode")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->accountcode, v->value, sizeof(CLINE_OPTS->accountcode));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "mohinterpret") || !strcasecmp(v->name, "musiconhold")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->mohinterpret, v->value, sizeof(CLINE_OPTS->mohinterpret));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "mohsuggest")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->mohsuggest, v->value, sizeof(CLINE_OPTS->mohsuggest));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "callgroup")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->callgroup = ast_get_group(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "pickupgroup")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->pickupgroup = ast_get_group(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "immediate")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE | TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->immediate = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "cancallforward")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->cancallforward = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "mailbox")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->mailbox, v->value, sizeof(CLINE_OPTS->mailbox));
+                               continue;
+                       }
+               } else if ( !strcasecmp(v->name, "parkinglot")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_copy_string(CLINE_OPTS->parkinglot, v->value, sizeof(CLINE_OPTS->parkinglot));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "hasvoicemail")) {
+                       if (type & (TYPE_LINE)) {
+                               if (ast_true(v->value) && ast_strlen_zero(CLINE->mailbox)) {
+                                       ast_copy_string(CLINE->mailbox, CLINE->name, sizeof(CLINE->mailbox));
+                               }
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "callreturn")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->callreturn = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "threewaycalling")) {
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               CLINE_OPTS->threewaycalling = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "setvar")) {
+                       if (type & (TYPE_LINE)) {
+                               CLINE->chanvars = add_var(v->value, CLINE->chanvars);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "earlyrtp")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               CDEV_OPTS->earlyrtp = ast_true(v->value);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "host")) {
+                       if (type & (TYPE_DEVICE)) {
+                               if (ast_get_ip(&CDEV->addr, v->value)) {
+                                       ast_log(LOG_WARNING, "Bad IP '%s' at line %d.\n", v->value, v->lineno);
+                               }
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "port")) {
+                       if (type & (TYPE_DEF_DEVICE)) {
+                               CDEV->addr.sin_port = htons(atoi(v->value));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "device")) {
+                       if (type & (TYPE_DEVICE)) {
+                               ast_copy_string(CDEV_OPTS->id, v->value, sizeof(CDEV_OPTS->id));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
+                       if (type & (TYPE_DEVICE)) {
+                               CDEV->ha = ast_append_ha(v->name, v->value, CDEV->ha, NULL);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "allow")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               ast_parse_allow_disallow(&CDEV_OPTS->confprefs, &CDEV_OPTS->confcapability, v->value, 1);
+                               continue;
+                       }
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_parse_allow_disallow(&CLINE_OPTS->confprefs, &CLINE_OPTS->confcapability, v->value, 1);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "disallow")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               ast_parse_allow_disallow(&CDEV_OPTS->confprefs, &CDEV_OPTS->confcapability, v->value, 0);
+                               continue;
+                       }
+                       if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
+                               ast_parse_allow_disallow(&CLINE_OPTS->confprefs, &CLINE_OPTS->confcapability, v->value, 0);
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "version")) {
+                       if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
+                               ast_copy_string(CDEV_OPTS->version_id, v->value, sizeof(CDEV_OPTS->version_id));
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "line")) {
+                       if (type & (TYPE_DEVICE)) {
+                               struct skinny_line *l;
+                               AST_LIST_TRAVERSE(&lines, l, all) {
+                                       if (!strcasecmp(v->value, l->name) && !l->prune) {
+
+                                               /* FIXME: temp solution about line conflicts */
+                                               struct skinny_device *d;
+                                               struct skinny_line *l2;
+                                               int lineinuse = 0;
+                                               AST_LIST_TRAVERSE(&devices, d, list) {
+                                                       AST_LIST_TRAVERSE(&d->lines, l2, list) {
+                                                               if (l2 == l && strcasecmp(d->id, CDEV->id)) {
+                                                                       ast_log(LOG_WARNING, "Line %s already used by %s. Not connecting to %s.\n", l->name, d->name, CDEV->name);
+                                                                       lineinuse++;
+                                                               }
+                                                       }
+                                               }
+                                               if (!lineinuse) {
+                                                       if (!AST_LIST_FIRST(&CDEV->lines)) {
+                                                               CDEV->activeline = l;
+                                                       }
+                                                       lineInstance++;
+                                                       AST_LIST_INSERT_HEAD(&CDEV->lines, l, list);
+                                               }
+                                               break;
+                                       }
+                               }
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "speeddial")) {
+                       if (type & (TYPE_DEVICE)) {
+                               struct skinny_speeddial *sd;
+                               if (!(sd = ast_calloc(1, sizeof(*sd)))) {
+                                       ast_log(LOG_WARNING, "Unable to allocate memory for speeddial %s. Ignoring speeddial.\n", v->name);
+                                       continue;
+                               } else {
+                                       char buf[256];
+                                       char *stringp = buf, *exten, *context, *label;
+                                               ast_copy_string(buf, v->value, sizeof(buf));
+                                       exten = strsep(&stringp, ",");
+                                       if ((context = strchr(exten, '@'))) {
+                                               *context++ = '\0';
+                                       }
+                                       label = stringp;
+                                       ast_mutex_init(&sd->lock);
+                                       ast_copy_string(sd->exten, exten, sizeof(sd->exten));
+                                       if (!ast_strlen_zero(context)) {
+                                               sd->isHint = 1;
+                                               sd->instance = lineInstance++;
+                                               ast_copy_string(sd->context, context, sizeof(sd->context));
+                                       } else {
+                                               sd->isHint = 0;
+                                               sd->instance = speeddialInstance++;
+                                               sd->context[0] = '\0';
+                                       }
+                                       ast_copy_string(sd->label, S_OR(label, exten), sizeof(sd->label));
+                                       sd->parent = CDEV;
+                                       AST_LIST_INSERT_HEAD(&CDEV->speeddials, sd, list);
+                               }
+                               continue;
+                       }
+               } else if (!strcasecmp(v->name, "addon")) {
+                       if (type & (TYPE_DEVICE)) {
+                               struct skinny_addon *a;
+                               if (!(a = ast_calloc(1, sizeof(*a)))) {
+                                       ast_log(LOG_WARNING, "Unable to allocate memory for addon %s. Ignoring addon.\n", v->name);
+                                       continue;
+                               } else {
+                                       ast_mutex_init(&a->lock);
+                                       ast_copy_string(a->type, v->value, sizeof(a->type));
+                                       AST_LIST_INSERT_HEAD(&CDEV->addons, a, list);
+                               }
+                               continue;
+                       }
+
+               } else {
+                       ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
+                       continue;
+               }
+               ast_log(LOG_WARNING, "Invalid category used: %s at line %d\n", v->name, v->lineno);
+       }
+ }
+ static struct skinny_line *config_line(const char *lname, struct ast_variable *v)
+ {
+       struct skinny_line *l, *temp;
+       int update = 0;
+       ast_log(LOG_NOTICE, "Configuring skinny line %s.\n", lname);
+
+       /* We find the old line and remove it just before the new
+          line is created */
+       AST_LIST_LOCK(&lines);
+       AST_LIST_TRAVERSE(&lines, temp, all) {
+               if (!strcasecmp(lname, temp->name) && temp->prune) {
+                       update = 1;
+                       break;
+               }
+       }
+
+       if (!(l=ast_calloc(1, sizeof(*l)))) {
+               ast_verb(1, "Unable to allocate memory for line %s.\n", lname);
+               AST_LIST_UNLOCK(&lines);
+               return NULL;
+       }
+
+       memcpy(l, default_line, sizeof(*default_line));
+       ast_mutex_init(&l->lock);
+       ast_copy_string(l->name, lname, sizeof(l->name));
+       AST_LIST_INSERT_TAIL(&lines, l, all);
+
+       ast_mutex_lock(&l->lock);
+       AST_LIST_UNLOCK(&lines);
+
+       config_parse_variables(TYPE_LINE, l, v);
+                       
+       if (!ast_strlen_zero(l->mailbox)) {
+               char *cfg_mailbox, *cfg_context;
+               cfg_context = cfg_mailbox = ast_strdupa(l->mailbox);
+               ast_verb(3, "Setting mailbox '%s' on line %s\n", cfg_mailbox, l->name);
+               strsep(&cfg_context, "@");
+               if (ast_strlen_zero(cfg_context))
+                        cfg_context = "default";
+               l->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "skinny MWI subsciption", l,
+                       AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, cfg_mailbox,
+                       AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, cfg_context,
+                       AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
+                       AST_EVENT_IE_END);
+       }
+       ast_mutex_unlock(&l->lock);
+       
+       /* We do not want to unlink or free the line yet, it needs
+          to be available to detect a device reconfig when we load the
+          devices.  Old lines will be pruned after the reload completes */
+
+       ast_verb(3, "%s config for line '%s'\n", update ? "Updated" : (skinnyreload ? "Reloaded" : "Created"), l->name);
+
+       return l;
+ }
+ static struct skinny_device *config_device(const char *dname, struct ast_variable *v)
+ {
+       struct skinny_device *d, *temp;
+       struct skinny_line *l, *ltemp;
+       struct skinny_subchannel *sub;
+       int update = 0;
+       ast_log(LOG_NOTICE, "Configuring skinny device %s.\n", dname);
+
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE(&devices, temp, list) {
+               if (!strcasecmp(dname, temp->name) && temp->prune) {
+                       update = 1;
+                       break;
+               }
+       }
+
+       if (!(d = ast_calloc(1, sizeof(*d)))) {
+               ast_verb(1, "Unable to allocate memory for device %s.\n", dname);
+               AST_LIST_UNLOCK(&devices);
+               return NULL;
+       }
+       memcpy(d, default_device, sizeof(*default_device));
+       ast_mutex_init(&d->lock);
+       ast_copy_string(d->name, dname, sizeof(d->name));
+       AST_LIST_INSERT_TAIL(&devices, d, list);
+
+       ast_mutex_lock(&d->lock);
+       AST_LIST_UNLOCK(&devices);
+       config_parse_variables(TYPE_DEVICE, d, v);
+       if (!AST_LIST_FIRST(&d->lines)) {
+               ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
+               ast_mutex_unlock(&d->lock);
+               return NULL;
+       }
+       if (/*d->addr.sin_addr.s_addr && */!ntohs(d->addr.sin_port)) {
+               d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
+       }
+       if (skinnyreload){
+               AST_LIST_LOCK(&devices);
+               AST_LIST_TRAVERSE(&devices, temp, list) {
+                       if (strcasecmp(d->id, temp->id) || !temp->prune || !temp->session) {
+                               continue;
+                       }
+                       ast_mutex_lock(&d->lock);
+                       d->session = temp->session;
+                       d->session->device = d;
+
+                       AST_LIST_LOCK(&d->lines);
+                       AST_LIST_TRAVERSE(&d->lines, l, list){
+                               l->device = d;  
+
+                               AST_LIST_LOCK(&temp->lines);
+                               AST_LIST_TRAVERSE(&temp->lines, ltemp, list) {
+                                       if (strcasecmp(l->name, ltemp->name)) {
+                                               continue;
+                                       }
+                                       ast_mutex_lock(&ltemp->lock);
+                                       l->instance = ltemp->instance;
+                                       l->hookstate = ltemp->hookstate;
+                                       if (!AST_LIST_EMPTY(&ltemp->sub)) {
+                                               ast_mutex_lock(&l->lock);
+                                               l->sub = ltemp->sub;
+                                               AST_LIST_TRAVERSE(&l->sub, sub, list) {
+                                                       sub->parent = l;
+                                               }
+                                               ast_mutex_unlock(&l->lock);
+                                       }
+                                       ast_mutex_unlock(&ltemp->lock);
+                               }
+                               AST_LIST_UNLOCK(&temp->lines);
+                       }
+                       AST_LIST_UNLOCK(&d->lines);
+                       ast_mutex_unlock(&d->lock);
+               }
+               AST_LIST_UNLOCK(&devices);
        }
-       cfg = ast_config_load(config, config_flags);
 
-       /* We *must* have a config file otherwise stop immediately */
-       if (!cfg) {
-               ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled\n", config);
-               return -1;
-       }
+       ast_mutex_unlock(&d->lock);
+
+       ast_verb(3, "%s config for device '%s'\n", update ? "Updated" : (skinnyreload ? "Reloaded" : "Created"), d->name);
+       
+       return d;
+
+ }
+ static int config_load(void)
+ {
+       int on = 1;
+       struct ast_config *cfg;
+       char *cat;
+       struct skinny_device *d;
+       struct skinny_line *l;
+       int oldport = ntohs(bindaddr.sin_port);
+       struct ast_flags config_flags = { 0 };
+       
+       ast_log(LOG_NOTICE, "Configuring skinny from %s\n", config);
+  
+       if (gethostname(ourhost, sizeof(ourhost))) {
+               ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled.\n");
+               return 0;
+       }
+       cfg = ast_config_load(config, config_flags);
+  
+       /* We *must* have a config file otherwise stop immediately */
+       if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
+               ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled.\n", config);
+               return -1;
+       }
        memset(&bindaddr, 0, sizeof(bindaddr));
        memset(&default_prefs, 0, sizeof(default_prefs));
 
-       /* Initialize copy of current global_regcontext for later use in removing stale contexts */
-       ast_copy_string(oldcontexts, regcontext, sizeof(oldcontexts));
-       oldregcontext = oldcontexts;
-
        /* Copy the default jb config over global_jbconf */
        memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
 
        /* load the general section */
-       v = ast_variable_browse(cfg, "general");
-       while (v) {
-               /* handle jb conf */
-               if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
-                       v = v->next;
-                       continue;
-               }
-
-               /* Create the interface list */
-               if (!strcasecmp(v->name, "bindaddr")) {
-                       if (!(hp = ast_gethostbyname(v->value, &ahp))) {
-                               ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
-                       } else {
-                               memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
-                       }
-               } else if (!strcasecmp(v->name, "keepalive")) {
-                       keep_alive = atoi(v->value);
-               } else if (!strcasecmp(v->name, "vmexten")) {
-                       ast_copy_string(vmexten, v->value, sizeof(vmexten));
-               } else if (!strcasecmp(v->name, "regcontext")) {
-                       ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
-                       stringp = newcontexts;
-                       /* Let's remove any contexts that are no longer defined in regcontext */
-                       cleanup_stale_contexts(stringp, oldregcontext);
-                       /* Create contexts if they don't exist already */
-                       while ((context = strsep(&stringp, "&"))) {
-                               ast_copy_string(used_context, context, sizeof(used_context));
-                               ast_context_find_or_create(NULL, NULL, context, "Skinny");
-                       }
-                       ast_copy_string(regcontext, v->value, sizeof(regcontext));
-               } else if (!strcasecmp(v->name, "dateformat")) {
-                       memcpy(date_format, v->value, sizeof(date_format));
-               } else if (!strcasecmp(v->name, "tos")) {
-                       if (ast_str2tos(v->value, &tos))
-                               ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
-               } else if (!strcasecmp(v->name, "tos_audio")) {
-                       if (ast_str2tos(v->value, &tos_audio))
-                               ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
-               } else if (!strcasecmp(v->name, "tos_video")) {
-                       if (ast_str2tos(v->value, &tos_video))
-                               ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
-               } else if (!strcasecmp(v->name, "cos")) {
-                       if (ast_str2cos(v->value, &cos))
-                               ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
-               } else if (!strcasecmp(v->name, "cos_audio")) {
-                       if (ast_str2cos(v->value, &cos_audio))
-                               ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
-               } else if (!strcasecmp(v->name, "cos_video")) {
-                       if (ast_str2cos(v->value, &cos_video))
-                               ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
-               } else if (!strcasecmp(v->name, "allow")) {
-                       ast_parse_allow_disallow(&default_prefs, &default_capability, v->value, 1);
-               } else if (!strcasecmp(v->name, "disallow")) {
-                       ast_parse_allow_disallow(&default_prefs, &default_capability, v->value, 0);
-               } else if (!strcasecmp(v->name, "bindport")) {
-                       if (sscanf(v->value, "%d", &ourport) == 1) {
-                               bindaddr.sin_port = htons(ourport);
-                       } else {
-                               ast_log(LOG_WARNING, "Invalid bindport '%s' at line %d of %s\n", v->value, v->lineno, config);
-                       }
-               }
-               v = v->next;
-       }
+       cat = ast_category_browse(cfg, "general");
+       config_parse_variables(TYPE_GENERAL, NULL, ast_variable_browse(cfg, "general"));
 
        if (ntohl(bindaddr.sin_addr.s_addr)) {
                __ourip = bindaddr.sin_addr;
@@ -6304,23 +7196,26 @@ static int reload_config(void)
        }
        bindaddr.sin_family = AF_INET;
 
-       /* load the device sections */
-       cat = ast_category_browse(cfg, NULL);
-       while(cat) {
-               if (!strcasecmp(cat, "general")) {
-                       /* Nothing to do */
-               } else {
-                       d = build_device(cat, ast_variable_browse(cfg, cat));
-                       if (d) {
-                               ast_verb(3, "Added device '%s'\n", d->name);
-                               ast_mutex_lock(&devicelock);
-                               d->next = devices;
-                               devices = d;
-                               ast_mutex_unlock(&devicelock);
-                       }
-               }
+       /* load the lines sections */
+       default_line->confcapability = default_capability;
+       default_line->confprefs = default_prefs;
+       config_parse_variables(TYPE_DEF_LINE, default_line, ast_variable_browse(cfg, "lines"));
+       cat = ast_category_browse(cfg, "lines");
+       while (cat && strcasecmp(cat, "general") && strcasecmp(cat, "devices")) {
+               l = config_line(cat, ast_variable_browse(cfg, cat));
                cat = ast_category_browse(cfg, cat);
        }
+               
+       /* load the devices sections */
+       default_device->confcapability = default_capability;
+       default_device->confprefs = default_prefs;
+       config_parse_variables(TYPE_DEF_DEVICE, default_device, ast_variable_browse(cfg, "devices"));
+       cat = ast_category_browse(cfg, "devices");
+       while (cat && strcasecmp(cat, "general") && strcasecmp(cat, "lines")) {
+               d = config_device(cat, ast_variable_browse(cfg, cat));
+               cat = ast_category_browse(cfg, cat);
+       }
+
        ast_mutex_lock(&netlock);
        if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
                close(skinnysock);
@@ -6331,6 +7226,7 @@ static int reload_config(void)
                if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
                        ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s\n", errno, strerror(errno));
                        ast_config_destroy(cfg);
+                       ast_mutex_unlock(&netlock);
                        return 0;
                }
                if (skinnysock < 0) {
@@ -6343,21 +7239,23 @@ static int reload_config(void)
                                close(skinnysock);
                                skinnysock = -1;
                                ast_config_destroy(cfg);
+                               ast_mutex_unlock(&netlock);
                                return 0;
                        }
-                       if (listen(skinnysock,DEFAULT_SKINNY_BACKLOG)) {
+                       if (listen(skinnysock, DEFAULT_SKINNY_BACKLOG)) {
                                        ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
                                                ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
                                                        strerror(errno));
                                        close(skinnysock);
                                        skinnysock = -1;
                                        ast_config_destroy(cfg);
+                                       ast_mutex_unlock(&netlock);
                                        return 0;
                        }
                        ast_verb(2, "Skinny listening on %s:%d\n",
                                        ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
-                       ast_netsock_set_qos(skinnysock, tos, cos, "Skinny");
-                       ast_pthread_create_background(&accept_t,NULL, accept_thread, NULL);
+                       ast_netsock_set_qos(skinnysock, qos.tos, qos.cos, "Skinny");
+                       ast_pthread_create_background(&accept_t, NULL, accept_thread, NULL);
                }
        }
        ast_mutex_unlock(&netlock);
@@ -6367,57 +7265,116 @@ static int reload_config(void)
 
 static void delete_devices(void)
 {
-       struct skinny_device *d, *dlast;
-       struct skinny_line *l, *llast;
-       struct skinny_speeddial *sd, *sdlast;
-       struct skinny_addon *a, *alast;
+       struct skinny_device *d;
+       struct skinny_line *l;
+       struct skinny_speeddial *sd;
+       struct skinny_addon *a;
 
-       ast_mutex_lock(&devicelock);
+       AST_LIST_LOCK(&devices);
+       AST_LIST_LOCK(&lines);
 
        /* Delete all devices */
-       for (d=devices;d;) {
+       while ((d = AST_LIST_REMOVE_HEAD(&devices, list))) {
                /* Delete all lines for this device */
-               for (l=d->lines;l;) {
-                       llast = l;
-                       l = l->next;
-                       ast_mutex_destroy(&llast->lock);
-                       ast_free(llast);
+               while ((l = AST_LIST_REMOVE_HEAD(&d->lines, list))) {
+                       AST_LIST_REMOVE(&lines, l, all);
+                       free(l);
                }
                /* Delete all speeddials for this device */
-               for (sd=d->speeddials;sd;) {
-                       sdlast = sd;
-                       sd = sd->next;
-                       ast_mutex_destroy(&sdlast->lock);
-                       ast_free(sdlast);
+               while ((sd = AST_LIST_REMOVE_HEAD(&d->speeddials, list))) {
+                       free(sd);
                }
                /* Delete all addons for this device */
-               for (a=d->addons;a;) {
-                       alast = a;
-                       a = a->next;
-                       ast_mutex_destroy(&alast->lock);
-                       ast_free(alast);
-               }
-               dlast = d;
-               d = d->next;
-               ast_free(dlast);
-       }
-       devices=NULL;
-       ast_mutex_unlock(&devicelock);
+               while ((a = AST_LIST_REMOVE_HEAD(&d->addons, list))) {
+                       free(a);
+               } 
+               free(d);
+       }
+       AST_LIST_UNLOCK(&lines);
+       AST_LIST_UNLOCK(&devices);
 }
 
-#if 0
-/*
- * XXX This never worked properly anyways.
- * Let's get rid of it, until we can fix it.
- */
-static int reload(void)
+int skinny_reload(void)
 {
-       delete_devices();
-       reload_config();
-       restart_monitor();
-       return 0;
+       struct skinny_device *d;
+       struct skinny_line *l;
+       struct skinny_speeddial *sd;
+       struct skinny_addon *a;
+       struct skinny_req *req;
+
+       if (skinnyreload) {
+               ast_verb(3, "Chan_skinny is already reloading.\n");
+               return 0;
+       }
+
+       skinnyreload = 1;
+
+       /* Mark all devices and lines as candidates to be pruned */
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE(&devices, d, list) {
+               d->prune = 1;
+       }
+       AST_LIST_UNLOCK(&devices);
+
+       AST_LIST_LOCK(&lines);
+       AST_LIST_TRAVERSE(&lines, l, all) {
+               l->prune = 1;
+       }
+       AST_LIST_UNLOCK(&lines);
+
+        config_load();
+
+       /* Remove any devices that no longer exist in the config */
+       AST_LIST_LOCK(&devices);
+       AST_LIST_TRAVERSE_SAFE_BEGIN(&devices, d, list) {
+               if (!d->prune) {
+                       continue;
+               }
+               ast_verb(3, "Removing device '%s'\n", d->name);
+               /* Delete all lines for this device. 
+                  We do not want to free the line here, that
+                  will happen below. */
+               while ((l = AST_LIST_REMOVE_HEAD(&d->lines, list))) {
+               }
+               /* Delete all speeddials for this device */
+               while ((sd = AST_LIST_REMOVE_HEAD(&d->speeddials, list))) {
+                       free(sd);
+               }
+               /* Delete all addons for this device */
+               while ((a = AST_LIST_REMOVE_HEAD(&d->addons, list))) {
+                       free(a);
+               }
+               AST_LIST_REMOVE_CURRENT(list);
+               free(d);
+       }
+       AST_LIST_TRAVERSE_SAFE_END;
+       AST_LIST_UNLOCK(&devices);
+
+       AST_LIST_LOCK(&lines);  
+       AST_LIST_TRAVERSE_SAFE_BEGIN(&lines, l, all) {
+               if (l->prune) {
+                       AST_LIST_REMOVE_CURRENT(all);
+                       free(l);
+               }
+       }
+       AST_LIST_TRAVERSE_SAFE_END;
+       AST_LIST_UNLOCK(&lines);  
+
+       AST_LIST_TRAVERSE(&devices, d, list) {
+               /* Do a soft reset to re-register the devices after
+                  cleaning up the removed devices and lines */
+               if (d->session) {
+                       ast_verb(3, "Restarting device '%s'\n", d->name);
+                       if ((req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE))) {
+                               req->data.reset.resetType = 2;
+                               transmit_response(d, req);
+                       }
+               }
+       }
+       
+       skinnyreload = 0;
+        return 0;
 }
-#endif
 
 static int load_module(void)
 {
@@ -6427,7 +7384,7 @@ static int load_module(void)
                soft_key_template_default[res].softKeyEvent = htolel(soft_key_template_default[res].softKeyEvent);
        }
        /* load and parse config */
-       res = reload_config();
+       res = config_load();
        if (res == -1) {
                return AST_MODULE_LOAD_DECLINE;
        }
@@ -6438,8 +7395,14 @@ static int load_module(void)
                return -1;
        }
 
-       ast_rtp_proto_register(&skinny_rtp);
-       ast_cli_register_multiple(cli_skinny, sizeof(cli_skinny) / sizeof(struct ast_cli_entry));
+       ast_rtp_glue_register(&skinny_rtp_glue);
+       ast_cli_register_multiple(cli_skinny, ARRAY_LEN(cli_skinny));
+
+       ast_manager_register_xml("SKINNYdevices", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_skinny_show_devices);
+       ast_manager_register_xml("SKINNYshowdevice", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_skinny_show_device);
+       ast_manager_register_xml("SKINNYlines", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_skinny_show_lines);
+       ast_m