Bring all app_rpt and chan_usbradio stuff up to date
authorJim Dixon <telesistant@hotmail.com>
Fri, 16 May 2008 00:51:14 +0000 (00:51 +0000)
committerJim Dixon <telesistant@hotmail.com>
Fri, 16 May 2008 00:51:14 +0000 (00:51 +0000)
git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@116731 65c4cc65-6c06-0410-ace0-fbb531ad65f3

apps/app_rpt.c
channels/Makefile
channels/chan_usbradio.c
channels/xpmr/sinetabx.h
channels/xpmr/xpmr.c
channels/xpmr/xpmr.h
channels/xpmr/xpmr_coef.h

index cf64d12..fa8a563 100644 (file)
@@ -1,7 +1,9 @@
+#define        NEW_ASTERISK
+/* #define OLD_ASTERISK */
 /*
  * Asterisk -- An open source telephony toolkit.
  *
 /*
  * Asterisk -- An open source telephony toolkit.
  *
- * Copyright (C) 2002-2005, Jim Dixon, WB6NIL
+ * Copyright (C) 2002-2008, Jim Dixon, WB6NIL
  *
  * Jim Dixon, WB6NIL <jim@lambdatel.com>
  * Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
  *
  * Jim Dixon, WB6NIL <jim@lambdatel.com>
  * Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
  * the GNU General Public License Version 2. See the LICENSE file
  * at the top of the source tree.
  */
  * the GNU General Public License Version 2. See the LICENSE file
  * at the top of the source tree.
  */
-
 /*! \file
  *
  * \brief Radio Repeater / Remote Base program 
 /*! \file
  *
  * \brief Radio Repeater / Remote Base program 
- *  version 0.48 06/13/06
+ *  version 0.115 5/12/08 2055 EDT
  * 
  * \author Jim Dixon, WB6NIL <jim@lambdatel.com>
  *
  * \note Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
  * 
  * \author Jim Dixon, WB6NIL <jim@lambdatel.com>
  *
  * \note Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
- * 
+ * \note Steven Henke, W9SH, <w9sh@arrl.net> added a few features here and there.
+ *
  * See http://www.zapatatelephony.org/app_rpt.html
  *
  *
  * See http://www.zapatatelephony.org/app_rpt.html
  *
  *
  *
  * status cmds:
  *
  *
  * status cmds:
  *
- *  1 - Force ID
- *  2 - Give Time of Day
- *  3 - Give software Version
+ *  1 - Force ID (global)
+ *  2 - Give Time of Day (global)
+ *  3 - Give software Version (global)
+ *  11 - Force ID (local only)
+ *  12 - Give Time of Day (local only)
  *
  * cop (control operator) cmds:
  *
  *  1 - System warm boot
  *  2 - System enable
  *  3 - System disable
  *
  * cop (control operator) cmds:
  *
  *  1 - System warm boot
  *  2 - System enable
  *  3 - System disable
- *  4 - Test Tone On
+ *  4 - Test Tone On/Off
  *  5 - Dump System Variables on Console (debug)
  *  6 - PTT (phone mode only)
  *  5 - Dump System Variables on Console (debug)
  *  6 - PTT (phone mode only)
+ *  7 - Time out timer enable
+ *  8 - Time out timer disable
+ *  9 - Autopatch enable
+ *  10 - Autopatch disable
+ *  11 - Link enable
+ *  12 - Link disable
+ *  13 - Query System State
+ *  14 - Change System State
+ *  15 - Scheduler Enable
+ *  16 - Scheduler Disable
+ *  17 - User functions (time, id, etc) enable
+ *  18 - User functions (time, id, etc) disable
+ *  19 - Select alternate hang timer
+ *  20 - Select standard hang timer 
+ *  21 - Enable Parrot Mode
+ *  22 - Disable Parrot Mode
+ *  23 - Birdbath (Current Parrot Cleanup/Flush)
+ *  24 - Flush all telemetry
+ *  25 - Query last node un-keyed
+ *  26 - Query all nodes keyed/unkeyed
+ *  30 - Recall Memory Setting in Attached Xcvr
+ *  31 - Channel Selector for Parallel Programmed Xcvr
+ *  32 - Touchtone pad test: command + Digit string + # to playback all digits pressed
  *
  * ilink cmds:
  *
  *
  * ilink cmds:
  *
  *  4 - Enter command mode on specified link
  *  5 - System status
  *  6 - Disconnect all links
  *  4 - Enter command mode on specified link
  *  5 - System status
  *  6 - Disconnect all links
+ *  11 - Disconnect a previously permanently connected link
+ *  12 - Permanently connect specified link -- monitor only
+ *  13 - Permanently connect specified link -- tranceive
+ *  15 - Full system status (all nodes)
+ *  16 - Reconnect links disconnected with "disconnect all links"
+ *  200 thru 215 - (Send DTMF 0-9,*,#,A-D) (200=0, 201=1, 210=*, etc)
  *
  * remote cmds:
  *
  *
  * remote cmds:
  *
  *  118 - Scan Up Fast
  *  119 - Transmit allowing auto-tune
  *  140 - Link Status (brief)
  *  118 - Scan Up Fast
  *  119 - Transmit allowing auto-tune
  *  140 - Link Status (brief)
+ *  200 thru 215 - (Send DTMF 0-9,*,#,A-D) (200=0, 201=1, 210=*, etc)
  *
  *
+ * playback cmds:
+ *  specify the name of the file to be played (for example, 25=rpt/foo)
  *
  *
  * 'duplex' modes:  (defaults to duplex=2)
  *
  *
  * 'duplex' modes:  (defaults to duplex=2)
 
 /* maximum digits in DTMF buffer, and seconds after * for DTMF command timeout */
 
 
 /* maximum digits in DTMF buffer, and seconds after * for DTMF command timeout */
 
+#ifdef OLD_ASTERISK
+#define ast_free free
+#define ast_malloc malloc
+#define ast_strdup strdup
+#endif
+
+
 #define        MAXDTMF 32
 #define        MAXMACRO 2048
 #define        MAXDTMF 32
 #define        MAXMACRO 2048
-#define        MAXGOSUB 2048
+#define        MAXLINKLIST 512
+#define        LINKLISTTIME 10000
+#define        LINKLISTSHORTTIME 200
+#define        LINKPOSTTIME 30000
+#define        LINKPOSTSHORTTIME 200
+#define        KEYPOSTTIME 30000
+#define        KEYPOSTSHORTTIME 200
 #define        MACROTIME 100
 #define        MACROTIME 100
-#define        GOSUBTIME 100
 #define        MACROPTIME 500
 #define        MACROPTIME 500
-#define        GOSUBPTIME 500
 #define        DTMF_TIMEOUT 3
 #define        DTMF_TIMEOUT 3
+#define        KENWOOD_RETRIES 5
+#define        TOPKEYN 32
+#define        TOPKEYWAIT 3
+#define        TOPKEYMAXSTR 30
+
+#define        AUTHTELLTIME 7000
+#define        AUTHTXTIME 1000
+#define        AUTHLOGOUTTIME 25000
 
 #ifdef __RPT_NOTCH
 #define        MAXFILTERS 10
 
 #ifdef __RPT_NOTCH
 #define        MAXFILTERS 10
 
 #define        DISC_TIME 10000  /* report disc after 10 seconds of no connect */
 #define        MAX_RETRIES 5
 
 #define        DISC_TIME 10000  /* report disc after 10 seconds of no connect */
 #define        MAX_RETRIES 5
+#define        MAX_RETRIES_PERM 1000000000
 
 #define        REDUNDANT_TX_TIME 2000
 
 #define        RETRY_TIMER_MS 5000
 
 
 #define        REDUNDANT_TX_TIME 2000
 
 #define        RETRY_TIMER_MS 5000
 
+#define        PATCH_DIALPLAN_TIMEOUT 1500
+
+#ifdef OLD_ASTERISK
+#define        START_DELAY 10
+#else
+#define        START_DELAY 2
+#endif
+
+#define        RPT_LOCKOUT_SECS 10
+
 #define MAXPEERSTR 31
 #define        MAXREMSTR 15
 
 #define        DELIMCHR ','
 #define        QUOTECHR 34
 
 #define MAXPEERSTR 31
 #define        MAXREMSTR 15
 
 #define        DELIMCHR ','
 #define        QUOTECHR 34
 
+#define        MONITOR_DISK_BLOCKS_PER_MINUTE 38
+
+#define        DEFAULT_MONITOR_MIN_DISK_BLOCKS 10000
+#define        DEFAULT_REMOTE_INACT_TIMEOUT (15 * 60)
+#define        DEFAULT_REMOTE_TIMEOUT (60 * 60)
+#define        DEFAULT_REMOTE_TIMEOUT_WARNING (3 * 60)
+#define        DEFAULT_REMOTE_TIMEOUT_WARNING_FREQ 30
+
 #define        NODES "nodes"
 #define        NODES "nodes"
+#define        EXTNODES "extnodes"
 #define MEMORY "memory"
 #define MACRO "macro"
 #define MEMORY "memory"
 #define MACRO "macro"
-#define GOSUB "gosub"
 #define        FUNCTIONS "functions"
 #define TELEMETRY "telemetry"
 #define MORSE "morse"
 #define        FUNCTIONS "functions"
 #define TELEMETRY "telemetry"
 #define MORSE "morse"
+#define        TONEMACRO "tonemacro"
 #define        FUNCCHAR '*'
 #define        ENDCHAR '#'
 #define        FUNCCHAR '*'
 #define        ENDCHAR '#'
+#define        EXTNODEFILE "/var/lib/asterisk/rpt_extnodes"
+#define        NODENAMES "rpt/nodenames"
+#define        PARROTFILE "/tmp/parrot_%s_%u"
+
+#define        PARROTTIME 1000
 
 #define        DEFAULT_IOBASE 0x378
 
 
 #define        DEFAULT_IOBASE 0x378
 
+#define        DEFAULT_CIV_ADDR 0x58
+
 #define        MAXCONNECTTIME 5000
 
 #define MAXNODESTR 300
 
 #define        MAXCONNECTTIME 5000
 
 #define MAXNODESTR 300
 
+#define MAXNODELEN 16
+
+#define MAXIDENTLEN 32
+
 #define MAXPATCHCONTEXT 100
 
 #define ACTIONSIZE 32
 #define MAXPATCHCONTEXT 100
 
 #define ACTIONSIZE 32
 
 #define REM_SCANTIME 100
 
 
 #define REM_SCANTIME 100
 
+#define        DTMF_LOCAL_TIME 250
+#define        DTMF_LOCAL_STARTTIME 500
+
+#define        IC706_PL_MEMORY_OFFSET 50
+
+#define        VOX_ON_DEBOUNCE_COUNT 3
+#define        VOX_OFF_DEBOUNCE_COUNT 20
+#define        VOX_MAX_THRESHOLD 10000.0
+#define        VOX_MIN_THRESHOLD 3000.0
+#define        VOX_TIMEOUT_MS 5000
+#define        VOX_RECOVER_MS 500
+#define        SIMPLEX_PATCH_DELAY 25
+#define        SIMPLEX_PHONE_DELAY 25
+
+#define        STATPOST_PROGRAM "/usr/bin/wget,-q,--output-document=/dev/null,--no-check-certificate"
 
 
-enum {REM_OFF, REM_MONITOR, REM_TX};
+#define        ALLOW_LOCAL_CHANNELS
 
 
-enum {ID, PROC, TERM, COMPLETE, UNKEY, REMDISC, REMALREADY, REMNOTFOUND, REMGO,
-       CONNECTED, CONNFAIL, STATUS, TIMEOUT, ID1, STATS_TIME,
+enum {REM_OFF,REM_MONITOR,REM_TX};
+
+enum{ID,PROC,TERM,COMPLETE,UNKEY,REMDISC,REMALREADY,REMNOTFOUND,REMGO,
+       CONNECTED,CONNFAIL,STATUS,TIMEOUT,ID1, STATS_TIME, PLAYBACK,
        STATS_VERSION, IDTALKOVER, ARB_ALPHA, TEST_TONE, REV_PATCH,
        STATS_VERSION, IDTALKOVER, ARB_ALPHA, TEST_TONE, REV_PATCH,
-       TAILMSG, MACRO_NOTFOUND, GOSUB_NOTFOUND, MACRO_BUSY, GOSUB_BUSY, LASTNODEKEY};
+       TAILMSG, MACRO_NOTFOUND, MACRO_BUSY, LASTNODEKEY, FULLSTATUS,
+       MEMNOTFOUND, INVFREQ, REMMODE, REMLOGIN, REMXXX, REMSHORTSTATUS,
+       REMLONGSTATUS, LOGINREQ, SCAN, SCANSTAT, TUNE, SETREMOTE, TOPKEY,
+       TIMEOUT_WARNING, ACT_TIMEOUT_WARNING, LINKUNKEY, UNAUTHTX, PARROT,
+       STATS_TIME_LOCAL};
+
 
 
-enum {REM_SIMPLEX, REM_MINUS, REM_PLUS};
+enum {REM_SIMPLEX,REM_MINUS,REM_PLUS};
 
 
-enum {REM_LOWPWR, REM_MEDPWR, REM_HIPWR};
+enum {REM_LOWPWR,REM_MEDPWR,REM_HIPWR};
 
 
-enum {DC_INDETERMINATE, DC_REQ_FLUSH, DC_ERROR, DC_COMPLETE, DC_DOKEY};
+enum {DC_INDETERMINATE, DC_REQ_FLUSH, DC_ERROR, DC_COMPLETE, DC_COMPLETEQUIET, DC_DOKEY};
 
 
-enum {SOURCE_RPT, SOURCE_LNK, SOURCE_RMT, SOURCE_PHONE, SOURCE_DPHONE};
+enum {SOURCE_RPT, SOURCE_LNK, SOURCE_RMT, SOURCE_PHONE, SOURCE_DPHONE, SOURCE_ALT};
 
 
-enum {DLY_TELEM, DLY_ID, DLY_UNKEY, DLY_CALLTERM};
+enum {DLY_TELEM, DLY_ID, DLY_UNKEY, DLY_CALLTERM, DLY_COMP, DLY_LINKUNKEY, DLY_PARROT};
 
 
-enum {REM_MODE_FM, REM_MODE_USB, REM_MODE_LSB, REM_MODE_AM};
+enum {REM_MODE_FM,REM_MODE_USB,REM_MODE_LSB,REM_MODE_AM};
 
 
-enum {HF_SCAN_OFF, HF_SCAN_DOWN_SLOW, HF_SCAN_DOWN_QUICK,
-       HF_SCAN_DOWN_FAST, HF_SCAN_UP_SLOW, HF_SCAN_UP_QUICK, HF_SCAN_UP_FAST};
+enum {HF_SCAN_OFF,HF_SCAN_DOWN_SLOW,HF_SCAN_DOWN_QUICK,
+      HF_SCAN_DOWN_FAST,HF_SCAN_UP_SLOW,HF_SCAN_UP_QUICK,HF_SCAN_UP_FAST};
 
 #include "asterisk.h"
 
 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
 #include <signal.h>
 
 #include "asterisk.h"
 
 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
 #include <signal.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdlib.h>
 #include <search.h>
 #include <search.h>
+#include <sys/types.h>
 #include <sys/stat.h>
 #include <sys/stat.h>
+#include <errno.h>
 #include <dirent.h>
 #include <ctype.h>
 #include <dirent.h>
 #include <ctype.h>
+#include <sys/stat.h>
 #include <sys/time.h>
 #include <sys/file.h>
 #include <sys/ioctl.h>
 #include <sys/io.h>
 #include <sys/time.h>
 #include <sys/file.h>
 #include <sys/ioctl.h>
 #include <sys/io.h>
+#include <sys/vfs.h>
 #include <math.h>
 #include <math.h>
+#ifdef OLD_ASTERISK
+#include <linux/zaptel.h>
+#include <tonezone.h>
+#else
+#include <zaptel/zaptel.h>
+#include <zaptel/tonezone.h>
+#endif
 #include <netinet/in.h>
 #include <arpa/inet.h>
 
 #include "asterisk/utils.h"
 #include "asterisk/lock.h"
 #include "asterisk/file.h"
 #include <netinet/in.h>
 #include <arpa/inet.h>
 
 #include "asterisk/utils.h"
 #include "asterisk/lock.h"
 #include "asterisk/file.h"
+#include "asterisk/logger.h"
 #include "asterisk/channel.h"
 #include "asterisk/callerid.h"
 #include "asterisk/pbx.h"
 #include "asterisk/module.h"
 #include "asterisk/translate.h"
 #include "asterisk/features.h"
 #include "asterisk/channel.h"
 #include "asterisk/callerid.h"
 #include "asterisk/pbx.h"
 #include "asterisk/module.h"
 #include "asterisk/translate.h"
 #include "asterisk/features.h"
+#include "asterisk/options.h"
 #include "asterisk/cli.h"
 #include "asterisk/config.h"
 #include "asterisk/say.h"
 #include "asterisk/localtime.h"
 #include "asterisk/cli.h"
 #include "asterisk/config.h"
 #include "asterisk/say.h"
 #include "asterisk/localtime.h"
-#include "asterisk/app.h"
+#include "asterisk/cdr.h"
+#include "asterisk/options.h"
+#include "asterisk/manager.h"
+#include <termios.h>
 
 
-#include "asterisk/zapata.h"
+#ifdef NEW_ASTERISK
+struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
+#endif
+
+
+/* Start a tone-list going */
+int ast_playtones_start(struct ast_channel *chan, int vol, const char* tonelist, int interruptible);
+/*! Stop the tones from playing */
+void ast_playtones_stop(struct ast_channel *chan);
+
+static  char *tdesc = "Radio Repeater / Remote Base  version 0.115  5/12/2008";
 
 static char *app = "Rpt";
 
 static char *synopsis = "Radio Repeater/Remote Base Control System";
 
 static char *descrip = 
 
 static char *app = "Rpt";
 
 static char *synopsis = "Radio Repeater/Remote Base Control System";
 
 static char *descrip = 
-"  Rpt(nodename[,options]):  Radio Remote Link or Remote Base Link Endpoint Process.\n"
+"  Rpt(nodename[|options][|M][|*]):  \n"
+"    Radio Remote Link or Remote Base Link Endpoint Process.\n"
 "\n"
 "    Not specifying an option puts it in normal endpoint mode (where source\n"
 "    IP and nodename are verified).\n"
 "\n"
 "    Not specifying an option puts it in normal endpoint mode (where source\n"
 "    IP and nodename are verified).\n"
@@ -254,7 +393,7 @@ static char *descrip =
 "            this if you have checked security already (like with an IAX2\n"
 "            user/password or something).\n"
 "\n"
 "            this if you have checked security already (like with an IAX2\n"
 "            user/password or something).\n"
 "\n"
-"        Rannounce-string[,timeout[,timeout-destination]] - Amateur Radio\n"
+"        Rannounce-string[|timeout[|timeout-destination]] - Amateur Radio\n"
 "            Reverse Autopatch. Caller is put on hold, and announcement (as\n"
 "            specified by the 'announce-string') is played on radio system.\n"
 "            Users of radio system can access autopatch, dial specified\n"
 "            Reverse Autopatch. Caller is put on hold, and announcement (as\n"
 "            specified by the 'announce-string') is played on radio system.\n"
 "            Users of radio system can access autopatch, dial specified\n"
@@ -275,17 +414,66 @@ static char *descrip =
 "            this mode), the 'dphone_functions' parameter must be specified\n"
 "            for the node in 'rpt.conf'. Otherwise no DTMF control will be\n"
 "            available to the phone user.\n"
 "            this mode), the 'dphone_functions' parameter must be specified\n"
 "            for the node in 'rpt.conf'. Otherwise no DTMF control will be\n"
 "            available to the phone user.\n"
+"\n"
+"        S - Simplex Dumb Phone Control mode. This allows a regular phone user\n"
+"            audio-only access to the radio system. In this mode, the\n"
+"            transmitter is toggled on and off when the phone user presses the\n"
+"            funcchar (*) key on the telephone set. In addition, the transmitter\n"
+"            will turn off if the endchar (#) key is pressed. When a user first\n"
+"            calls in, the transmitter will be off, and the user can listen for\n"
+"            radio traffic. When the user wants to transmit, they press the *\n" 
+"            key, start talking, then press the * key again or the # key to turn\n"
+"            the transmitter off.  No other functions can be executed by the\n"
+"            user on the phone when this mode is selected. Note: If your\n"
+"            radio system is full-duplex, we recommend using either P or D\n"
+"            modes as they provide more flexibility.\n"
+"\n"
+"        q - Query Status. Sets channel variables and returns + 101 in plan.\n"
+"\n"
+"        M - Memory Channel Steer as MXX where XX is the memory channel number.\n"
+"\n"
+"        * - Alt Macro to execute (e.g. *7 for status)\n"
 "\n";
 "\n";
+;
 
 
-static unsigned int vmajor = 0;
-static unsigned int vminor = 47;
-
-static int debug = 0;  /* FIXME Set this >0 for extra debug output */
+static int debug = 0;  /* Set this >0 for extra debug output */
 static int nrpts = 0;
 
 static int nrpts = 0;
 
+static char remdtmfstr[] = "0123456789*#ABCD";
+
+enum {TOP_TOP,TOP_WON,WON_BEFREAD,BEFREAD_AFTERREAD};
+
+int max_chan_stat [] = {22000,1000,22000,100,22000,2000,22000};
+
+#define NRPTSTAT 7
+
+struct rpt_chan_stat
+{
+       struct timeval last;
+       long long total;
+       unsigned long count;
+       unsigned long largest;
+       struct timeval largest_time;
+};
+
 char *discstr = "!!DISCONNECT!!";
 char *discstr = "!!DISCONNECT!!";
-static char *remote_rig_ft897 = "ft897";
-static char *remote_rig_rbi = "rbi";
+char *newkeystr = "!NEWKEY!";
+static char *remote_rig_ft897="ft897";
+static char *remote_rig_rbi="rbi";
+static char *remote_rig_kenwood="kenwood";
+static char *remote_rig_tm271="tm271";
+static char *remote_rig_ic706="ic706";
+static char *remote_rig_rtx150="rtx150";
+static char *remote_rig_rtx450="rtx450";
+static char *remote_rig_ppp16="ppp16";                 // parallel port programmable 16 channels
+
+#define ISRIG_RTX(x) ((!strcmp(x,remote_rig_rtx150)) || (!strcmp(x,remote_rig_rtx450)))
+#define        IS_XPMR(x) (!strncasecmp(x->rxchanname,"rad",3))
+
+#ifdef OLD_ASTERISK
+STANDARD_LOCAL_USER;
+LOCAL_USER_DECL;
+#endif
 
 #define        MSWAIT 200
 #define        HANGTIME 5000
 
 #define        MSWAIT 200
 #define        HANGTIME 5000
@@ -296,9 +484,44 @@ static char *remote_rig_rbi = "rbi";
 #define POLITEID 30000
 #define FUNCTDELAY 1500
 
 #define POLITEID 30000
 #define FUNCTDELAY 1500
 
-static  pthread_t rpt_master_thread;
+#define        MAXXLAT 20
+#define        MAXXLATTIME 3
+
+#define MAX_SYSSTATES 10
+
+struct vox {
+       float   speech_energy;
+       float   noise_energy;
+       int     enacount;
+       char    voxena;
+       char    lastvox;
+       int     offdebcnt;
+       int     ondebcnt;
+} ;
+
+#define        mymax(x,y) ((x > y) ? x : y)
+#define        mymin(x,y) ((x < y) ? x : y)
+
+struct rpt_topkey
+{
+char   node[TOPKEYMAXSTR];
+int    timesince;
+int    keyed;
+} ;
+
+struct rpt_xlat
+{
+char   funccharseq[MAXXLAT];
+char   endcharseq[MAXXLAT];
+char   passchars[MAXXLAT];
+int    funcindex;
+int    endindex;
+time_t lastone;
+} ;
 
 
-struct timeval cancel_atimeout = { 0, 0 };
+static time_t  starttime = 0;
+
+static  pthread_t rpt_master_thread;
 
 struct rpt;
 
 
 struct rpt;
 
@@ -309,11 +532,17 @@ struct rpt_link
        char    mode;                   /* 1 if in tx mode */
        char    isremote;
        char    phonemode;
        char    mode;                   /* 1 if in tx mode */
        char    isremote;
        char    phonemode;
+       char    phonevox;               /* vox the phone */
        char    name[MAXNODESTR];       /* identifier (routing) string */
        char    lasttx;
        char    name[MAXNODESTR];       /* identifier (routing) string */
        char    lasttx;
+       char    lasttx1;
        char    lastrx;
        char    lastrx;
+       char    lastrealrx;
+       char    lastrx1;
        char    connected;
        char    hasconnected;
        char    connected;
        char    hasconnected;
+       char    perma;
+       char    thisconnected;
        char    outbound;
        char    disced;
        char    killme;
        char    outbound;
        char    disced;
        char    killme;
@@ -321,11 +550,31 @@ struct rpt_link
        long    disctime;
        long    retrytimer;
        long    retxtimer;
        long    disctime;
        long    retrytimer;
        long    retxtimer;
+       long    rerxtimer;
        int     retries;
        int     retries;
+       int     max_retries;
        int     reconnects;
        long long connecttime;
        struct ast_channel *chan;       
        struct ast_channel *pchan;      
        int     reconnects;
        long long connecttime;
        struct ast_channel *chan;       
        struct ast_channel *pchan;      
+       char    linklist[MAXLINKLIST];
+       time_t  linklistreceived;
+       long    linklisttimer;
+       int     dtmfed;
+       int linkunkeytocttimer;
+       struct timeval lastlinktv;
+       struct  ast_frame *lastf1,*lastf2;
+       struct  rpt_chan_stat chan_stat[NRPTSTAT];
+       struct vox vox;
+       char wasvox;
+       int voxtotimer;
+       char voxtostate;
+       char newkey;
+#ifdef OLD_ASTERISK
+        AST_LIST_HEAD(, ast_frame) rxq;
+#else
+       AST_LIST_HEAD_NOLOCK(, ast_frame) rxq;
+#endif
 } ;
 
 struct rpt_lstat
 } ;
 
 struct rpt_lstat
@@ -337,7 +586,9 @@ struct rpt_lstat
        char    mode;
        char    outbound;
        char    reconnects;
        char    mode;
        char    outbound;
        char    reconnects;
+       char    thisconnected;
        long long       connecttime;
        long long       connecttime;
+       struct  rpt_chan_stat chan_stat[NRPTSTAT];
 } ;
 
 struct rpt_tele
 } ;
 
 struct rpt_tele
@@ -349,6 +600,8 @@ struct rpt_tele
        int     mode;
        struct rpt_link mylink;
        char param[TELEPARAMSIZE];
        int     mode;
        struct rpt_link mylink;
        char param[TELEPARAMSIZE];
+       int     submode;
+       unsigned int parrot;
        pthread_t threadid;
 } ;
 
        pthread_t threadid;
 } ;
 
@@ -374,85 +627,163 @@ struct telem_defaults
 } ;
 
 
 } ;
 
 
+struct sysstate
+{
+       char txdisable;
+       char totdisable;
+       char linkfundisable;
+       char autopatchdisable;
+       char schedulerdisable;
+       char userfundisable;
+       char alternatetail;
+};
+
+/* rpt cmd support */
+#define CMD_DEPTH 1
+#define CMD_STATE_IDLE 0
+#define CMD_STATE_BUSY 1
+#define CMD_STATE_READY 2
+#define CMD_STATE_EXECUTING 3
+
+struct rpt_cmd_struct
+{
+    int state;
+    int functionNumber;
+    char param[MAXDTMF];
+    char digits[MAXDTMF];
+    int command_source;
+};
+
 static struct rpt
 {
        ast_mutex_t lock;
 static struct rpt
 {
        ast_mutex_t lock;
+       ast_mutex_t remlock;
+       ast_mutex_t statpost_lock;
        struct ast_config *cfg;
        char reload;
        struct ast_config *cfg;
        char reload;
+       char xlink;                                                                     // cross link state of a share repeater/remote radio
+       unsigned int statpost_seqno;
 
        char *name;
        char *rxchanname;
        char *txchanname;
 
        char *name;
        char *rxchanname;
        char *txchanname;
-       char *remote;
+       char remote;
+       char *remoterig;
+       struct  rpt_chan_stat chan_stat[NRPTSTAT];
+       unsigned int scram;
 
        struct {
 
        struct {
-               char ourcontext[80];
-               char ourcallerid[80];
-               char acctcode[21];
-               char ident[80];
-               char tonezone[80];
+               char *ourcontext;
+               char *ourcallerid;
+               char *acctcode;
+               char *ident;
+               char *tonezone;
                char simple;
                char simple;
-               char functions[80];
-               char link_functions[80];
-               char phone_functions[80];
-               char dphone_functions[80];
-               char nodes[80];
+               char *functions;
+               char *link_functions;
+               char *phone_functions;
+               char *dphone_functions;
+               char *alt_functions;
+               char *nodes;
+               char *extnodes;
+               char *extnodefile;
                int hangtime;
                int hangtime;
+               int althangtime;
                int totime;
                int idtime;
                int tailmessagetime;
                int tailsquashedtime;
                int duplex;
                int politeid;
                int totime;
                int idtime;
                int tailmessagetime;
                int tailsquashedtime;
                int duplex;
                int politeid;
-               char *tailmsgbuf;
-               AST_DECLARE_APP_ARGS(tailmsg,
-                       AST_APP_ARG(msgs)[100];
-               );
-               char memory[80];
-               char macro[80];
-               char gosub[80];
-               char startupmacro[80];
-               char startupgosub[80];
+               char *tailmessages[500];
+               int tailmessagemax;
+               char    *memory;
+               char    *macro;
+               char    *tonemacro;
+               char    *startupmacro;
                int iobase;
                int iobase;
+               char *ioport;
                char funcchar;
                char endchar;
                char nobusyout;
                char funcchar;
                char endchar;
                char nobusyout;
+               char notelemtx;
+               char propagate_dtmf;
+               char propagate_phonedtmf;
+               char linktolink;
+               unsigned char civaddr;
+               struct rpt_xlat inxlat;
+               struct rpt_xlat outxlat;
+               char *archivedir;
+               int authlevel;
+               char *csstanzaname;
+               char *skedstanzaname;
+               char *txlimitsstanzaname;
+               long monminblocks;
+               int remoteinacttimeout;
+               int remotetimeout;
+               int remotetimeoutwarning;
+               int remotetimeoutwarningfreq;
+               int sysstate_cur;
+               struct sysstate s[MAX_SYSSTATES];
+               char parrotmode;
+               int parrottime;
+               char *rptnode;
+               char remote_mars;
+               int voxtimeout_ms;
+               int voxrecover_ms;
+               int simplexpatchdelay;
+               int simplexphonedelay;
+               char *statpost_program;
+               char *statpost_url;
        } p;
        struct rpt_link links;
        int unkeytocttimer;
        } p;
        struct rpt_link links;
        int unkeytocttimer;
+       time_t lastkeyedtime;
+       time_t lasttxkeyedtime;
        char keyed;
        char keyed;
+       char txkeyed;
        char exttx;
        char localtx;
        char remoterx;
        char remotetx;
        char remoteon;
        char exttx;
        char localtx;
        char remoterx;
        char remotetx;
        char remoteon;
+       char remtxfreqok;
        char tounkeyed;
        char tonotify;
        char tounkeyed;
        char tonotify;
-       char enable;
        char dtmfbuf[MAXDTMF];
        char macrobuf[MAXMACRO];
        char dtmfbuf[MAXDTMF];
        char macrobuf[MAXMACRO];
-       char gosubbuf[MAXGOSUB];
        char rem_dtmfbuf[MAXDTMF];
        char lastdtmfcommand[MAXDTMF];
        char cmdnode[50];
        char rem_dtmfbuf[MAXDTMF];
        char lastdtmfcommand[MAXDTMF];
        char cmdnode[50];
-       struct ast_channel *rxchannel, *txchannel;
-       struct ast_channel *pchannel, *txpchannel, *remchannel;
+       char nowchan;                                           // channel now
+       char waschan;                                           // channel selected initially or by command
+       char bargechan;                                         // barge in channel
+       char macropatch;                                        // autopatch via tonemacro state
+       char parrotstate;
+       int  parrottimer;
+       unsigned int parrotcnt;
+       struct ast_channel *rxchannel,*txchannel, *monchannel, *parrotchannel;
+       struct ast_channel *pchannel,*txpchannel, *zaprxchannel, *zaptxchannel;
+       struct ast_channel *voxchannel;
+       struct ast_frame *lastf1,*lastf2;
        struct rpt_tele tele;
        struct rpt_tele tele;
-       struct timeval lasttv, curtv;
-       pthread_t rpt_call_thread, rpt_thread;
-       time_t dtmf_time, rem_dtmf_time, dtmf_time_rem;
-       int tailtimer, totimer, idtimer, txconf, conf, callmode, cidx, scantimer, tmsgtimer, skedtimer;
-       int mustid, tailid;
+       struct timeval lasttv,curtv;
+       pthread_t rpt_call_thread,rpt_thread;
+       time_t dtmf_time,rem_dtmf_time,dtmf_time_rem;
+       int calldigittimer;
+       int tailtimer,totimer,idtimer,txconf,conf,callmode,cidx,scantimer,tmsgtimer,skedtimer;
+       int mustid,tailid;
        int tailevent;
        int telemrefcount;
        int tailevent;
        int telemrefcount;
-       int dtmfidx, rem_dtmfidx;
-       int dailytxtime, dailykerchunks, totalkerchunks, dailykeyups, totalkeyups, timeouts;
+       int dtmfidx,rem_dtmfidx;
+       int dailytxtime,dailykerchunks,totalkerchunks,dailykeyups,totalkeyups,timeouts;
        int totalexecdcommands, dailyexecdcommands;
        int totalexecdcommands, dailyexecdcommands;
-       long retxtimer;
+       long    retxtimer;
+       long    rerxtimer;
        long long totaltxtime;
        char mydtmf;
        char exten[AST_MAX_EXTENSION];
        long long totaltxtime;
        char mydtmf;
        char exten[AST_MAX_EXTENSION];
-       char freq[MAXREMSTR], rxpl[MAXREMSTR], txpl[MAXREMSTR];
+       char freq[MAXREMSTR],rxpl[MAXREMSTR],txpl[MAXREMSTR];
        char offset;
        char powerlevel;
        char txplon;
        char offset;
        char powerlevel;
        char txplon;
@@ -461,16 +792,18 @@ static struct rpt
        char tunerequest;
        char hfscanmode;
        int hfscanstatus;
        char tunerequest;
        char hfscanmode;
        int hfscanstatus;
+       char hfscanstop;
        char lastlinknode[MAXNODESTR];
        char lastlinknode[MAXNODESTR];
-       char stopgen;
+       char savednodes[MAXNODESTR];
+       int stopgen;
        char patchfarenddisconnect;
        char patchnoct;
        char patchquiet;
        char patchcontext[MAXPATCHCONTEXT];
        int patchdialtime;
        int macro_longest;
        char patchfarenddisconnect;
        char patchnoct;
        char patchquiet;
        char patchcontext[MAXPATCHCONTEXT];
        int patchdialtime;
        int macro_longest;
-       int gosub_longest;
        int phone_longestfunc;
        int phone_longestfunc;
+       int alt_longestfunc;
        int dphone_longestfunc;
        int link_longestfunc;
        int longestfunc;
        int dphone_longestfunc;
        int link_longestfunc;
        int longestfunc;
@@ -479,31 +812,80 @@ static struct rpt
        int tailmessagen;
        time_t disgorgetime;
        time_t lastthreadrestarttime;
        int tailmessagen;
        time_t disgorgetime;
        time_t lastthreadrestarttime;
-       long macrotimer;
-       long gosubtimer;
-       char lastnodewhichkeyedusup[MAXNODESTR];
+       long    macrotimer;
+       char    lastnodewhichkeyedusup[MAXNODESTR];
+       int     dtmf_local_timer;
+       char    dtmf_local_str[100];
+       struct ast_filestream *monstream,*parrotstream;
+       char    loginuser[50];
+       char    loginlevel[10];
+       long    authtelltimer;
+       long    authtimer;
+       int iofd;
+       time_t start_time,last_activity_time;
+       char    lasttone[32];
+       struct rpt_tele *active_telem;
+       struct  rpt_topkey topkey[TOPKEYN];
+       int topkeystate;
+       time_t topkeytime;
+       int topkeylong;
+       struct vox vox;
+       char wasvox;
+       int voxtotimer;
+       char voxtostate;
+       int linkposttimer;                      
+       int keyposttimer;                       
+       char newkey;
+       char inpadtest;
+#ifdef OLD_ASTERISK
+       AST_LIST_HEAD(, ast_frame) txq;
+#else
+       AST_LIST_HEAD_NOLOCK(, ast_frame) txq;
+#endif
+       char txrealkeyed;
 #ifdef __RPT_NOTCH
        struct rptfilter
        {
 #ifdef __RPT_NOTCH
        struct rptfilter
        {
-               char desc[100];
-               float x0;
-               float x1;
-               float x2;
-               float y0;
-               float y1;
-               float y2;
-               float gain;
-               float const0;
-               float const1;
-               float const2;
+               char    desc[100];
+               float   x0;
+               float   x1;
+               float   x2;
+               float   y0;
+               float   y1;
+               float   y2;
+               float   gain;
+               float   const0;
+               float   const1;
+               float   const2;
        } filters[MAXFILTERS];
 #endif
 #ifdef _MDC_DECODE_H_
        mdc_decoder_t *mdc;
        unsigned short lastunit;
 #endif
        } filters[MAXFILTERS];
 #endif
 #ifdef _MDC_DECODE_H_
        mdc_decoder_t *mdc;
        unsigned short lastunit;
 #endif
+       struct rpt_cmd_struct cmdAction;
 } rpt_vars[MAXRPTS];   
 
 } rpt_vars[MAXRPTS];   
 
+struct nodelog {
+struct nodelog *next;
+struct nodelog *prev;
+time_t timestamp;
+char archivedir[MAXNODESTR];
+char str[MAXNODESTR * 2];
+} nodelog;
+
+static int service_scan(struct rpt *myrpt);
+static int set_mode_ft897(struct rpt *myrpt, char newmode);
+static int set_mode_ic706(struct rpt *myrpt, char newmode);
+static int simple_command_ft897(struct rpt *myrpt, char command);
+static int setrem(struct rpt *myrpt);
+static int setrtx_check(struct rpt *myrpt);
+static int channel_revert(struct rpt *myrpt);
+static int channel_steer(struct rpt *myrpt, char *data);
+
+AST_MUTEX_DEFINE_STATIC(nodeloglock);
+
+AST_MUTEX_DEFINE_STATIC(nodelookuplock);
 
 #ifdef APP_RPT_LOCK_DEBUG
 
 
 #ifdef APP_RPT_LOCK_DEBUG
 
@@ -511,8 +893,8 @@ static struct rpt
 
 #define        MAXLOCKTHREAD 100
 
 
 #define        MAXLOCKTHREAD 100
 
-#define        rpt_mutex_lock(x)       _rpt_mutex_lock(x, myrpt, __LINE__)
-#define        rpt_mutex_unlock(x)     _rpt_mutex_unlock(x, myrpt, __LINE__)
+#define rpt_mutex_lock(x) _rpt_mutex_lock(x,myrpt,__LINE__)
+#define rpt_mutex_unlock(x) _rpt_mutex_unlock(x,myrpt,__LINE__)
 
 struct lockthread
 {
 
 struct lockthread
 {
@@ -531,40 +913,42 @@ struct by_lightning
        struct lockthread lockthread;
 } lock_ring[32];
 
        struct lockthread lockthread;
 } lock_ring[32];
 
-
 int lock_ring_index = 0;
 
 AST_MUTEX_DEFINE_STATIC(locklock);
 
 static struct lockthread *get_lockthread(pthread_t id)
 {
 int lock_ring_index = 0;
 
 AST_MUTEX_DEFINE_STATIC(locklock);
 
 static struct lockthread *get_lockthread(pthread_t id)
 {
-       int     i;
+int    i;
 
 
-       for (i = 0; i < MAXLOCKTHREAD; i++) {
-               if (lockthreads[i].id == id)
-                       return(&lockthreads[i]);
+       for(i = 0; i < MAXLOCKTHREAD; i++)
+       {
+               if (lockthreads[i].id == id) return(&lockthreads[i]);
        }
        }
-       return NULL;
+       return(NULL);
 }
 
 static struct lockthread *put_lockthread(pthread_t id)
 {
 }
 
 static struct lockthread *put_lockthread(pthread_t id)
 {
-       int     i;
+int    i;
 
 
-       for (i = 0; i < MAXLOCKTHREAD; i++) {
+       for(i = 0; i < MAXLOCKTHREAD; i++)
+       {
                if (lockthreads[i].id == id)
                        return(&lockthreads[i]);
        }
                if (lockthreads[i].id == id)
                        return(&lockthreads[i]);
        }
-       for (i = 0; i < MAXLOCKTHREAD; i++) {
-               if (!lockthreads[i].id) {
+       for(i = 0; i < MAXLOCKTHREAD; i++)
+       {
+               if (!lockthreads[i].id)
+               {
                        lockthreads[i].lockcount = 0;
                        lockthreads[i].lastlock = 0;
                        lockthreads[i].lastunlock = 0;
                        lockthreads[i].id = id;
                        lockthreads[i].lockcount = 0;
                        lockthreads[i].lastlock = 0;
                        lockthreads[i].lastunlock = 0;
                        lockthreads[i].id = id;
-                       return &lockthreads[i];
+                       return(&lockthreads[i]);
                }
        }
                }
        }
-       return NULL;
+       return(NULL);
 }
 
 
 }
 
 
@@ -572,10 +956,9 @@ static void rpt_mutex_spew(void)
 {
        struct by_lightning lock_ring_copy[32];
        int lock_ring_index_copy;
 {
        struct by_lightning lock_ring_copy[32];
        int lock_ring_index_copy;
-       int i, j;
+       int i,j;
        long long diff;
        long long diff;
-       char a[100] = "";
-       struct ast_tm tm;
+       char a[100];
        struct timeval lasttv;
 
        ast_mutex_lock(&locklock);
        struct timeval lasttv;
 
        ast_mutex_lock(&locklock);
@@ -584,27 +967,30 @@ static void rpt_mutex_spew(void)
        ast_mutex_unlock(&locklock);
 
        lasttv.tv_sec = lasttv.tv_usec = 0;
        ast_mutex_unlock(&locklock);
 
        lasttv.tv_sec = lasttv.tv_usec = 0;
-       for (i = 0; i < 32; i++) {
+       for(i = 0 ; i < 32 ; i++)
+       {
                j = (i + lock_ring_index_copy) % 32;
                j = (i + lock_ring_index_copy) % 32;
-               ast_strftime(a, sizeof(a) - 1, "%m/%d/%Y %H:%M:%S",
-                       ast_localtime(&lock_ring_copy[j].tv, &tm, NULL));
+               strftime(a,sizeof(a) - 1,"%m/%d/%Y %H:%M:%S",
+                       localtime(&lock_ring_copy[j].tv.tv_sec));
                diff = 0;
                diff = 0;
-               if (lasttv.tv_sec) {
-                       diff = (lock_ring_copy[j].tv.tv_sec - lasttv.tv_sec) * 1000000;
+               if(lasttv.tv_sec)
+               {
+                       diff = (lock_ring_copy[j].tv.tv_sec - lasttv.tv_sec)
+                               * 1000000;
                        diff += (lock_ring_copy[j].tv.tv_usec - lasttv.tv_usec);
                }
                lasttv.tv_sec = lock_ring_copy[j].tv.tv_sec;
                lasttv.tv_usec = lock_ring_copy[j].tv.tv_usec;
                        diff += (lock_ring_copy[j].tv.tv_usec - lasttv.tv_usec);
                }
                lasttv.tv_sec = lock_ring_copy[j].tv.tv_sec;
                lasttv.tv_usec = lock_ring_copy[j].tv.tv_usec;
-               if (!lock_ring_copy[j].tv.tv_sec)
-                       continue;
-               if (lock_ring_copy[j].line < 0) {
-                       ast_log(LOG_NOTICE, "LOCKDEBUG [#%d] UNLOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
-                               i - 31, -lock_ring_copy[j].line, lock_ring_copy[j].rpt->name,
-                               (int) lock_ring_copy[j].lockthread.id, diff, a, (int)lock_ring_copy[j].tv.tv_usec);
-               } else {
-                       ast_log(LOG_NOTICE, "LOCKDEBUG [#%d] LOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
-                               i - 31, lock_ring_copy[j].line, lock_ring_copy[j].rpt->name,
-                               (int) lock_ring_copy[j].lockthread.id, diff, a, (int)lock_ring_copy[j].tv.tv_usec);
+               if (!lock_ring_copy[j].tv.tv_sec) continue;
+               if (lock_ring_copy[j].line < 0)
+               {
+                       ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] UNLOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
+                               i - 31,-lock_ring_copy[j].line,lock_ring_copy[j].rpt->name,(int) lock_ring_copy[j].lockthread.id,diff,a,(int)lock_ring_copy[j].tv.tv_usec);
+               }
+               else
+               {
+                       ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] LOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
+                               i - 31,lock_ring_copy[j].line,lock_ring_copy[j].rpt->name,(int) lock_ring_copy[j].lockthread.id,diff,a,(int)lock_ring_copy[j].tv.tv_usec);
                }
        }
 }
                }
        }
 }
@@ -612,21 +998,22 @@ static void rpt_mutex_spew(void)
 
 static void _rpt_mutex_lock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
 {
 
 static void _rpt_mutex_lock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
 {
-       struct lockthread *t;
-       pthread_t id;
+struct lockthread *t;
+pthread_t id;
 
        id = pthread_self();
        ast_mutex_lock(&locklock);
        t = put_lockthread(id);
 
        id = pthread_self();
        ast_mutex_lock(&locklock);
        t = put_lockthread(id);
-       if (!t) {
+       if (!t)
+       {
                ast_mutex_unlock(&locklock);
                return;
        }
                ast_mutex_unlock(&locklock);
                return;
        }
-       if (t->lockcount) {
+       if (t->lockcount)
+       {
                int lastline = t->lastlock;
                ast_mutex_unlock(&locklock);
                int lastline = t->lastlock;
                ast_mutex_unlock(&locklock);
-               ast_log(LOG_NOTICE, "rpt_mutex_lock: Double lock request line %d node %s pid %x, last lock was line %d\n",
-                               line, myrpt->name, (int) t->id, lastline);
+               ast_log(LOG_NOTICE,"rpt_mutex_lock: Double lock request line %d node %s pid %x, last lock was line %d\n",line,myrpt->name,(int) t->id,lastline);
                rpt_mutex_spew();
                return;
        }
                rpt_mutex_spew();
                return;
        }
@@ -634,9 +1021,9 @@ static void _rpt_mutex_lock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
        t->lockcount = 1;
        gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
        lock_ring[lock_ring_index].rpt = myrpt;
        t->lockcount = 1;
        gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
        lock_ring[lock_ring_index].rpt = myrpt;
-       memcpy(&lock_ring[lock_ring_index].lockthread, t, sizeof(struct lockthread));
+       memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
        lock_ring[lock_ring_index++].line = line;
        lock_ring[lock_ring_index++].line = line;
-       if (lock_ring_index == 32)
+       if(lock_ring_index == 32)
                lock_ring_index = 0;
        ast_mutex_unlock(&locklock);
        ast_mutex_lock(lockp);
                lock_ring_index = 0;
        ast_mutex_unlock(&locklock);
        ast_mutex_lock(lockp);
@@ -645,21 +1032,22 @@ static void _rpt_mutex_lock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
 
 static void _rpt_mutex_unlock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
 {
 
 static void _rpt_mutex_unlock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
 {
-       struct lockthread *t;
-       pthread_t id;
+struct lockthread *t;
+pthread_t id;
 
        id = pthread_self();
        ast_mutex_lock(&locklock);
        t = put_lockthread(id);
 
        id = pthread_self();
        ast_mutex_lock(&locklock);
        t = put_lockthread(id);
-       if (!t) {
+       if (!t)
+       {
                ast_mutex_unlock(&locklock);
                return;
        }
                ast_mutex_unlock(&locklock);
                return;
        }
-       if (!t->lockcount) {
+       if (!t->lockcount)
+       {
                int lastline = t->lastunlock;
                ast_mutex_unlock(&locklock);
                int lastline = t->lastunlock;
                ast_mutex_unlock(&locklock);
-               ast_log(LOG_NOTICE, "rpt_mutex_lock: Double un-lock request line %d node %s pid %x, last un-lock was line %d\n",
-                               line, myrpt->name, (int) t->id, lastline);
+               ast_log(LOG_NOTICE,"rpt_mutex_lock: Double un-lock request line %d node %s pid %x, last un-lock was line %d\n",line,myrpt->name,(int) t->id,lastline);
                rpt_mutex_spew();
                return;
        }
                rpt_mutex_spew();
                return;
        }
@@ -667,9 +1055,9 @@ static void _rpt_mutex_unlock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
        t->lockcount = 0;
        gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
        lock_ring[lock_ring_index].rpt = myrpt;
        t->lockcount = 0;
        gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
        lock_ring[lock_ring_index].rpt = myrpt;
-       memcpy(&lock_ring[lock_ring_index].lockthread, t, sizeof(struct lockthread));
+       memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
        lock_ring[lock_ring_index++].line = -line;
        lock_ring[lock_ring_index++].line = -line;
-       if (lock_ring_index == 32)
+       if(lock_ring_index == 32)
                lock_ring_index = 0;
        ast_mutex_unlock(&locklock);
        ast_mutex_unlock(lockp);
                lock_ring_index = 0;
        ast_mutex_unlock(&locklock);
        ast_mutex_unlock(lockp);
@@ -683,25 +1071,205 @@ static void _rpt_mutex_unlock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
 #endif  /* APP_RPT_LOCK_DEBUG */
 
 /*
 #endif  /* APP_RPT_LOCK_DEBUG */
 
 /*
+* Return 1 if rig is multimode capable
+*/
+
+static int multimode_capable(struct rpt *myrpt)
+{
+       if(!strcmp(myrpt->remoterig, remote_rig_ft897))
+               return 1;
+       if(!strcmp(myrpt->remoterig, remote_rig_ic706))
+               return 1;
+       return 0;
+}      
+
+static void voxinit_rpt(struct rpt *myrpt,char enable)
+{
+
+       myrpt->vox.speech_energy = 0.0;
+       myrpt->vox.noise_energy = 0.0;
+       myrpt->vox.enacount = 0;
+       myrpt->vox.voxena = 0;
+       if (!enable) myrpt->vox.voxena = -1;
+       myrpt->vox.lastvox = 0;
+       myrpt->vox.ondebcnt = VOX_ON_DEBOUNCE_COUNT;
+       myrpt->vox.offdebcnt = VOX_OFF_DEBOUNCE_COUNT;
+       myrpt->wasvox = 0;
+       myrpt->voxtotimer = 0;
+       myrpt->voxtostate = 0;
+}
+
+static void voxinit_link(struct rpt_link *mylink,char enable)
+{
+
+       mylink->vox.speech_energy = 0.0;
+       mylink->vox.noise_energy = 0.0;
+       mylink->vox.enacount = 0;
+       mylink->vox.voxena = 0;
+       if (!enable) mylink->vox.voxena = -1;
+       mylink->vox.lastvox = 0;
+       mylink->vox.ondebcnt = VOX_ON_DEBOUNCE_COUNT;
+       mylink->vox.offdebcnt = VOX_OFF_DEBOUNCE_COUNT;
+       mylink->wasvox = 0;
+       mylink->voxtotimer = 0;
+       mylink->voxtostate = 0;
+}
+
+static int dovox(struct vox *v,short *buf,int bs)
+{
+
+       int i;
+       float   esquare = 0.0;
+       float   energy = 0.0;
+       float   threshold = 0.0;
+       
+       if (v->voxena < 0) return(v->lastvox);
+       for(i = 0; i < bs; i++)
+       {
+               esquare += (float) buf[i] * (float) buf[i];
+       }
+       energy = sqrt(esquare);
+
+       if (energy >= v->speech_energy)
+               v->speech_energy += (energy - v->speech_energy) / 4;
+       else
+               v->speech_energy += (energy - v->speech_energy) / 64;
+
+       if (energy >= v->noise_energy)
+               v->noise_energy += (energy - v->noise_energy) / 64;
+       else
+               v->noise_energy += (energy - v->noise_energy) / 4;
+       
+       if (v->voxena) threshold = v->speech_energy / 8;
+       else
+       {
+               threshold = mymax(v->speech_energy / 16,v->noise_energy * 2);
+               threshold = mymin(threshold,VOX_MAX_THRESHOLD);
+       }
+       threshold = mymax(threshold,VOX_MIN_THRESHOLD);
+       if (energy > threshold)
+       {
+               if (v->voxena) v->noise_energy *= 0.75;
+               v->voxena = 1;
+       } else  v->voxena = 0;
+       if (v->lastvox != v->voxena)
+       {
+               if (v->enacount++ >= ((v->lastvox) ? v->offdebcnt : v->ondebcnt))
+               {
+                       v->lastvox = v->voxena;
+                       v->enacount = 0;
+               }
+       } else v->enacount = 0;
+       return(v->lastvox);
+}
+
+
+
+
+/*
 * CLI extensions
 */
 
 /* Debug mode */
 * CLI extensions
 */
 
 /* Debug mode */
-static char *handle_cli_rpt_debug_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
-static char *handle_cli_rpt_dump(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
-static char *handle_cli_rpt_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
-static char *handle_cli_rpt_lstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
-static char *handle_cli_rpt_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
-static char *handle_cli_rpt_restart(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
-
-static struct ast_cli_entry cli_rpt[] = {
-       AST_CLI_DEFINE(handle_cli_rpt_debug_level, "Enable app_rpt debuggin"),
-       AST_CLI_DEFINE(handle_cli_rpt_dump,        "Dump app_rpt structs for debugging"),
-       AST_CLI_DEFINE(handle_cli_rpt_stats,       "Dump node statistics"),
-       AST_CLI_DEFINE(handle_cli_rpt_lstats,      "Dump link statistics"),
-       AST_CLI_DEFINE(handle_cli_rpt_reload,      "Reload app_rpt config"),
-       AST_CLI_DEFINE(handle_cli_rpt_restart,     "Restart app_rpt")
-};
+static int rpt_do_debug(int fd, int argc, char *argv[]);
+static int rpt_do_dump(int fd, int argc, char *argv[]);
+static int rpt_do_stats(int fd, int argc, char *argv[]);
+static int rpt_do_lstats(int fd, int argc, char *argv[]);
+static int rpt_do_nodes(int fd, int argc, char *argv[]);
+static int rpt_do_local_nodes(int fd, int argc, char *argv[]);
+static int rpt_do_reload(int fd, int argc, char *argv[]);
+static int rpt_do_restart(int fd, int argc, char *argv[]);
+static int rpt_do_fun(int fd, int argc, char *argv[]);
+static int rpt_do_fun1(int fd, int argc, char *argv[]);
+static int rpt_do_cmd(int fd, int argc, char *argv[]);
+
+static char debug_usage[] =
+"Usage: rpt debug level {0-7}\n"
+"       Enables debug messages in app_rpt\n";
+
+static char dump_usage[] =
+"Usage: rpt dump <nodename>\n"
+"       Dumps struct debug info to log\n";
+
+static char dump_stats[] =
+"Usage: rpt stats <nodename>\n"
+"       Dumps node statistics to console\n";
+
+static char dump_lstats[] =
+"Usage: rpt lstats <nodename>\n"
+"       Dumps link statistics to console\n";
+
+static char dump_nodes[] =
+"Usage: rpt nodes <nodename>\n"
+"       Dumps a list of directly and indirectly connected nodes to the console\n";
+
+static char usage_local_nodes[] =
+"Usage: rpt localnodes\n"
+"       Dumps a list of the locally configured node numbers to the console.\n";
+
+static char reload_usage[] =
+"Usage: rpt reload\n"
+"       Reloads app_rpt running config parameters\n";
+
+static char restart_usage[] =
+"Usage: rpt restart\n"
+"       Restarts app_rpt\n";
+
+static char fun_usage[] =
+"Usage: rpt fun <nodename> <command>\n"
+"       Send a DTMF function to a node\n";
+
+static char cmd_usage[] =
+"Usage: rpt cmd <nodename> <cmd-name> <cmd-index> <cmd-args.\n"
+"       Send a command to a node.\n        i.e. rpt cmd 2000 ilink 3 2001\n";
+
+#ifndef        NEW_ASTERISK
+
+static struct ast_cli_entry  cli_debug =
+        { { "rpt", "debug", "level" }, rpt_do_debug, 
+               "Enable app_rpt debugging", debug_usage };
+
+static struct ast_cli_entry  cli_dump =
+        { { "rpt", "dump" }, rpt_do_dump,
+               "Dump app_rpt structs for debugging", dump_usage };
+
+static struct ast_cli_entry  cli_stats =
+        { { "rpt", "stats" }, rpt_do_stats,
+               "Dump node statistics", dump_stats };
+
+static struct ast_cli_entry  cli_nodes =
+        { { "rpt", "nodes" }, rpt_do_nodes,
+               "Dump node list", dump_nodes };
+
+static struct ast_cli_entry  cli_local_nodes =
+        { { "rpt", "localnodes" }, rpt_do_local_nodes,
+               "Dump list of local node numbers", usage_local_nodes };
+
+static struct ast_cli_entry  cli_lstats =
+        { { "rpt", "lstats" }, rpt_do_lstats,
+               "Dump link statistics", dump_lstats };
+
+static struct ast_cli_entry  cli_reload =
+        { { "rpt", "reload" }, rpt_do_reload,
+               "Reload app_rpt config", reload_usage };
+
+static struct ast_cli_entry  cli_restart =
+        { { "rpt", "restart" }, rpt_do_restart,
+               "Restart app_rpt", restart_usage };
+
+static struct ast_cli_entry  cli_fun =
+        { { "rpt", "fun" }, rpt_do_fun,
+               "Execute a DTMF function", fun_usage };
+
+static struct ast_cli_entry  cli_fun1 =
+        { { "rpt", "fun1" }, rpt_do_fun1,
+               "Execute a DTMF function", fun_usage };
+
+static struct ast_cli_entry  cli_cmd =
+        { { "rpt", "cmd" }, rpt_do_cmd,
+               "Execute a DTMF function", cmd_usage };
+
+#endif
 
 /*
 * Telemetry defaults
 
 /*
 * Telemetry defaults
@@ -709,25 +1277,30 @@ static struct ast_cli_entry cli_rpt[] = {
 
 
 static struct telem_defaults tele_defs[] = {
 
 
 static struct telem_defaults tele_defs[] = {
-       {"ct1", "|t(350,0,100,3072)(500,0,100,3072)(660,0,100,3072)"},
-       {"ct2", "|t(660,880,150,3072)"},
-       {"ct3", "|t(440,0,150,3072)"},
-       {"ct4", "|t(550,0,150,3072)"},
-       {"ct5", "|t(660,0,150,3072)"},
-       {"ct6", "|t(880,0,150,3072)"},
-       {"ct7", "|t(660,440,150,3072)"},
-       {"ct8", "|t(700,1100,150,3072)"},
-       {"remotemon", "|t(1600,0,75,2048)"},
-       {"remotetx", "|t(2000,0,75,2048)(0,0,75,0)(1600,0,75,2048)"},
-       {"cmdmode", "|t(900,904,200,2048)"},
-       {"functcomplete", "|t(1000,0,100,2048)(0,0,100,0)(1000,0,100,2048)"}
+       {"ct1","|t(350,0,100,3072)(500,0,100,3072)(660,0,100,3072)"},
+       {"ct2","|t(660,880,150,3072)"},
+       {"ct3","|t(440,0,150,3072)"},
+       {"ct4","|t(550,0,150,3072)"},
+       {"ct5","|t(660,0,150,3072)"},
+       {"ct6","|t(880,0,150,3072)"},
+       {"ct7","|t(660,440,150,3072)"},
+       {"ct8","|t(700,1100,150,3072)"},
+       {"remotemon","|t(1600,0,75,2048)"},
+       {"remotetx","|t(2000,0,75,2048)(0,0,75,0)(1600,0,75,2048)"},
+       {"cmdmode","|t(900,904,200,2048)"},
+       {"functcomplete","|t(1000,0,100,2048)(0,0,100,0)(1000,0,100,2048)"}
 } ;
 
 /*
 } ;
 
 /*
-* Forward decl's - these suppress compiler warnings when funcs coded further down the file than their invocation
+* Forward decl's - these suppress compiler warnings when funcs coded further down the file than thier invokation
 */
 
 static int setrbi(struct rpt *myrpt);
 */
 
 static int setrbi(struct rpt *myrpt);
+static int set_ft897(struct rpt *myrpt);
+static int set_ic706(struct rpt *myrpt);
+static int setkenwood(struct rpt *myrpt);
+static int set_tm271(struct rpt *myrpt);
+static int setrbi_check(struct rpt *myrpt);
 
 
 
 
 
 
@@ -742,7 +1315,7 @@ static int function_status(struct rpt *myrpt, char *param, char *digitbuf, int c
 static int function_cop(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
 static int function_remote(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
 static int function_macro(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
 static int function_cop(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
 static int function_remote(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
 static int function_macro(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
-static int function_gosub(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
+static int function_playback(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
 /*
 * Function table
 */
 /*
 * Function table
 */
@@ -755,318 +1328,1287 @@ static struct function_table_tag function_table[] = {
        {"status", function_status},
        {"remote", function_remote},
        {"macro", function_macro},
        {"status", function_status},
        {"remote", function_remote},
        {"macro", function_macro},
-       {"gosub", function_gosub},
+       {"playback", function_playback}
 } ;
 
 } ;
 
-/*
-* Match a keyword in a list, and return index of string plus 1 if there was a match,
-* else return 0. If param is passed in non-null, then it will be set to the first character past the match
-*/
-
-static int matchkeyword(char *string, char **param, char *keywords[])
+static long diskavail(struct rpt *myrpt)
 {
 {
-       int     i, ls;
-       for (i = 0; keywords[i]; i++) {
-               ls = strlen(keywords[i]);
-               if (!ls) {
-                       *param = NULL;
-                       return 0;
-               }
-               if (!strncmp(string, keywords[i], ls)) {
-                       if (param)
-                               *param = string + ls;
-                       return i + 1; 
-               }
-       }
-       param = NULL;
-       return 0;
-}
-
-/*
-* Skip characters in string which are in charlist, and return a pointer to the
-* first non-matching character
-*/
+struct statfs statfsbuf;
 
 
-static char *skipchars(char *string, char *charlist)
-{
-       int i;  
-       while (*string) {
-               for (i = 0; charlist[i] ; i++) {
-                       if (*string == charlist[i]) {
-                               string++;
-                               break;
-                       }
-               }
-               if (!charlist[i])
-                       return string;
+       if (!myrpt->p.archivedir) return(0);
+       if (statfs(myrpt->p.archivedir,&statfsbuf) == -1)
+       {
+               ast_log(LOG_WARNING,"Cannot get filesystem size for %s node %s\n",
+                       myrpt->p.archivedir,myrpt->name);
+               return(-1);
        }
        }
-       return string;
-}      
-                                       
-
-
-static int myatoi(const char *str)
-{
-       int     ret;
-
-       if (str == NULL)
-               return -1;
-       /* leave this %i alone, non-base-10 input is useful here */
-       if (sscanf(str, "%i", &ret) != 1)
-               return -1;
-       return ret;
+       return(statfsbuf.f_bavail);
 }
 
 }
 
-
-#ifdef __RPT_NOTCH
-
-/* rpt filter routine */
-static void rpt_filter(struct rpt *myrpt, volatile short *buf, int len)
+static void flush_telem(struct rpt *myrpt)
 {
 {
-       int     i, j;
-       struct rptfilter *f;
-
-       for (i = 0; i < len; i++) {
-               for (j = 0; j < MAXFILTERS; j++) {
-                       f = &myrpt->filters[j];
-                       if (!*f->desc)
-                               continue;
-                       f->x0 = f->x1; f->x1 = f->x2;
-                       f->x2 = ((float)buf[i]) / f->gain;
-                       f->y0 = f->y1; f->y1 = f->y2;
-                       f->y2 =   (f->x0 + f->x2)     +  f->const0 * f->x1
-                               + (f->const1 * f->y0) + (f->const2 * f->y1);
-                       buf[i] = (short)f->y2;
-               }
+       struct rpt_tele *telem;
+       if(debug > 2)
+               ast_log(LOG_NOTICE, "flush_telem()!!");
+       rpt_mutex_lock(&myrpt->lock);
+       telem = myrpt->tele.next;
+       while(telem != &myrpt->tele)
+       {
+               if (telem->mode != SETREMOTE) ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
+               telem = telem->next;
        }
        }
+       rpt_mutex_unlock(&myrpt->lock);
 }
 }
-
-#endif
-
-/* Retrieve an int from a config file */
-static int retrieve_astcfgint(struct rpt *myrpt, const char *category, const char *name, int min, int max, int defl)
+/*
+       return via error priority
+*/
+static int priority_jump(struct rpt *myrpt, struct ast_channel *chan)
 {
 {
-       const char *var = ast_variable_retrieve(myrpt->cfg, category, name);
-       int ret;
+       int res=0;
 
 
-       if (var) {
-               ret = myatoi(var);
-               if (ret < min)
-                       ret = min;
-               else if (ret > max)
-                       ret = max;
-       } else
-               ret = defl;
-       return ret;
+       // if (ast_test_flag(&flags,OPT_JUMP) && ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101) == 0){
+       if (ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101) == 0){
+               res = 0;
+       } else {
+               res = -1;
+       }
+       return res;
 }
 }
-
-
-static void load_rpt_vars(int n, int init)
+/*
+*/
+static int linkcount(struct rpt *myrpt)
 {
 {
-       int     j;
-       struct ast_variable *vp, *var;
-       struct ast_config *cfg;
-       struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
-#ifdef __RPT_NOTCH
-       AST_DECLARE_APP_ARGS(strs,
-               AST_APP_ARG(str)[100];
-       );
-#endif
+       struct  rpt_link *l;
+       char *reverse_patch_state;
+       int numoflinks;
 
 
-       ast_verb(3, "%s config for repeater %s\n",
-                       (init) ? "Loading initial" : "Re-Loading", rpt_vars[n].name);
-       ast_mutex_lock(&rpt_vars[n].lock);
-       if (rpt_vars[n].cfg)
-               ast_config_destroy(rpt_vars[n].cfg);
-       cfg = ast_config_load("rpt.conf", config_flags);
-       if (!cfg) {
-               ast_mutex_unlock(&rpt_vars[n].lock);
-               ast_log(LOG_NOTICE, "Unable to open radio repeater configuration rpt.conf.  Radio Repeater disabled.\n");
-               pthread_exit(NULL);
-       }
-       rpt_vars[n].cfg = cfg;
-       /* Free previously malloc'ed buffer */
-       if (!init && rpt_vars[n].p.tailmsgbuf)
-               ast_free(rpt_vars[n].p.tailmsgbuf);
-       memset(&rpt_vars[n].p, 0, sizeof(rpt_vars[n].p));
-       if (init) {
-               /* clear all the fields in the structure after 'p' */
-               memset(&rpt_vars[n].p + sizeof(rpt_vars[0].p), 0, sizeof(rpt_vars[0]) - sizeof(rpt_vars[0].p) - offsetof(typeof(rpt_vars[0]), p));
-               rpt_vars[n].tele.next = &rpt_vars[n].tele;
-               rpt_vars[n].tele.prev = &rpt_vars[n].tele;
-               rpt_vars[n].rpt_thread = AST_PTHREADT_NULL;
-               rpt_vars[n].tailmessagen = 0;
-       }
-#ifdef __RPT_NOTCH
-       /* zot out filters stuff */
-       memset(&rpt_vars[n].filters, 0, sizeof(rpt_vars[n].filters));
-#endif
-
-       /* Defaults */
-       ast_copy_string(rpt_vars[n].p.ourcontext, rpt_vars[n].name, sizeof(rpt_vars[n].p.ourcontext));
-       rpt_vars[n].p.hangtime = HANGTIME;
-       rpt_vars[n].p.totime = TOTIME;
-       rpt_vars[n].p.duplex = 2;
-       rpt_vars[n].p.idtime = IDTIME;
-       rpt_vars[n].p.politeid = POLITEID;
-       ast_copy_string(rpt_vars[n].p.memory, MEMORY, sizeof(rpt_vars[n].p.memory));
-       ast_copy_string(rpt_vars[n].p.macro, MACRO, sizeof(rpt_vars[n].p.macro));
-       ast_copy_string(rpt_vars[n].p.gosub, GOSUB, sizeof(rpt_vars[n].p.gosub));
-       rpt_vars[n].p.iobase = DEFAULT_IOBASE;
-       ast_copy_string(rpt_vars[n].p.functions, FUNCTIONS, sizeof(rpt_vars[n].p.functions));
-       rpt_vars[n].p.simple = 1;
-       rpt_vars[n].p.funcchar = FUNCCHAR;
-       rpt_vars[n].p.endchar = ENDCHAR;
-       ast_copy_string(rpt_vars[n].p.nodes, NODES, sizeof(rpt_vars[n].p.nodes));
-
-       for (var = ast_variable_browse(cfg, rpt_vars[n].name); var; var = var->next) {
-               if (!strcmp(var->name, "context")) {
-                       ast_copy_string(rpt_vars[n].p.ourcontext, var->value, sizeof(rpt_vars[n].p.ourcontext));
-               } else if (!strcmp(var->name, "callerid")) {
-                       ast_copy_string(rpt_vars[n].p.ourcallerid, var->value, sizeof(rpt_vars[n].p.ourcallerid));
-               } else if (!strcmp(var->name, "accountcode")) {
-                       ast_copy_string(rpt_vars[n].p.acctcode, var->value, sizeof(rpt_vars[n].p.acctcode));
-               } else if (!strcmp(var->name, "idrecording")) {
-                       ast_copy_string(rpt_vars[n].p.ident, var->value, sizeof(rpt_vars[n].p.ident));
-               } else if (!strcmp(var->name, "hangtime")) {
-                       rpt_vars[n].p.hangtime = atoi(var->value);
-               } else if (!strcmp(var->name, "totime")) {
-                       rpt_vars[n].p.totime = atoi(var->value);
-               } else if (!strcmp(var->name, "tailmessagetime")) {
-                       rpt_vars[n].p.tailmessagetime = atoi(var->value);
-                       if (rpt_vars[n].p.tailmessagetime < 0)
-                               rpt_vars[n].p.tailmessagetime = 0;
-                       else if (rpt_vars[n].p.tailmessagetime > 2400000)
-                               rpt_vars[n].p.tailmessagetime = 2400000;
-               } else if (!strcmp(var->name, "tailsquashedtime")) {
-                       rpt_vars[n].p.tailsquashedtime = atoi(var->value);
-                       if (rpt_vars[n].p.tailsquashedtime < 0)
-                               rpt_vars[n].p.tailsquashedtime = 0;
-                       else if (rpt_vars[n].p.tailsquashedtime > 2400000)
-                               rpt_vars[n].p.tailsquashedtime = 2400000;
-               } else if (!strcmp(var->name, "duplex")) {
-                       rpt_vars[n].p.duplex = atoi(var->value);
-                       if (rpt_vars[n].p.duplex < 0)
-                               rpt_vars[n].p.duplex = 0;
-                       else if (rpt_vars[n].p.duplex > 4)
-                               rpt_vars[n].p.duplex = 4;
-               } else if (!strcmp(var->name, "idtime")) {
-                       rpt_vars[n].p.idtime = atoi(var->value);
-                       if (rpt_vars[n].p.idtime < 60000)
-                               rpt_vars[n].p.idtime = 60000;
-                       else if (rpt_vars[n].p.idtime > 2400000)
-                               rpt_vars[n].p.idtime = 2400000;
-               } else if (!strcmp(var->name, "politeid")) {
-                       rpt_vars[n].p.politeid = atoi(var->value);
-                       if (rpt_vars[n].p.politeid < 30000)
-                               rpt_vars[n].p.politeid = 30000;
-                       else if (rpt_vars[n].p.politeid > 300000)
-                               rpt_vars[n].p.politeid = 300000;
-               } else if (!strcmp(var->name, "tonezone")) {
-                       ast_copy_string(rpt_vars[n].p.tonezone, var->value, sizeof(rpt_vars[n].p.tonezone));
-               } else if (!strcmp(var->name, "tailmessagelist")) {
-                       rpt_vars[n].p.tailmsgbuf = ast_strdup(var->value);
-                       AST_STANDARD_APP_ARGS(rpt_vars[n].p.tailmsg, rpt_vars[n].p.tailmsgbuf);
-               } else if (!strcmp(var->name, "memory")) {
-                       ast_copy_string(rpt_vars[n].p.memory, var->value, sizeof(rpt_vars[n].p.memory));
-               } else if (!strcmp(var->name, "macro")) {
-                       ast_copy_string(rpt_vars[n].p.macro, var->value, sizeof(rpt_vars[n].p.macro));
-               } else if (!strcmp(var->name, "gosub")) {
-                       ast_copy_string(rpt_vars[n].p.gosub, var->value, sizeof(rpt_vars[n].p.gosub));
-               } else if (!strcmp(var->name, "startup_macro")) {
-                       ast_copy_string(rpt_vars[n].p.startupmacro, var->value, sizeof(rpt_vars[n].p.startupmacro));
-               } else if (!strcmp(var->name, "startup_gosub")) {
-                       ast_copy_string(rpt_vars[n].p.startupgosub, var->value, sizeof(rpt_vars[n].p.startupgosub));
-               } else if (!strcmp(var->name, "iobase")) {
-                       /* do not use atoi() here, we need to be able to have
-                          the input specified in hex or decimal so we use
-                          sscanf with a %i */
-                       if (sscanf(var->value, "%i", &rpt_vars[n].p.iobase) != 1)
-                               rpt_vars[n].p.iobase = DEFAULT_IOBASE;
-               } else if (!strcmp(var->name, "functions")) {
-                       rpt_vars[n].p.simple = 0;
-                       ast_copy_string(rpt_vars[n].p.functions, var->value, sizeof(rpt_vars[n].p.functions));
-               } else if (!strcmp(var->name, "link_functions")) {
-                       ast_copy_string(rpt_vars[n].p.link_functions, var->value, sizeof(rpt_vars[n].p.link_functions));
-               } else if (!strcmp(var->name, "phone_functions")) {
-                       ast_copy_string(rpt_vars[n].p.phone_functions, var->value, sizeof(rpt_vars[n].p.phone_functions));
-               } else if (!strcmp(var->name, "dphone_functions")) {
-                       ast_copy_string(rpt_vars[n].p.dphone_functions, var->value, sizeof(rpt_vars[n].p.dphone_functions));
-               } else if (!strcmp(var->name, "funcchar")) {
-                       rpt_vars[n].p.funcchar = *var->value;
-               } else if (!strcmp(var->name, "endchar")) {
-                       rpt_vars[n].p.endchar = *var->value;
-               } else if (!strcmp(var->name, "nobusyout")) {
-                       rpt_vars[n].p.nobusyout = ast_true(var->value);
-               } else if (!strcmp(var->name, "nodes")) {
-                       ast_copy_string(rpt_vars[n].p.nodes, var->value, sizeof(rpt_vars[n].p.nodes));
-#ifdef __RPT_NOTCH
-               } else if (!strcmp(var->name, "rxnotch")) {
-                       char *tmp = ast_strdupa(val);
-                       AST_STANDARD_APP_ARGS(strs, tmp);
-                       strs.argc &= ~1; /* force an even number, rounded down */
-                       if (strs.argc >= 2) {
-                               for (j = 0; j < strs.argc; j += 2) {
-                                       rpt_mknotch(atof(strs.str[j]), atof(strs.str[j + 1]),
-                                               &rpt_vars[n].filters[j >> 1].gain,
-                                               &rpt_vars[n].filters[j >> 1].const0,
-                                               &rpt_vars[n].filters[j >> 1].const1,
-                                               &rpt_vars[n].filters[j >> 1].const2);
-                                       sprintf(rpt_vars[n].filters[j >> 1].desc, "%s Hz, BW = %s",
-                                               strs.str[j], strs.str[j + 1]);
-                               }
-                       }
-#endif
+       reverse_patch_state = "DOWN";
+       numoflinks = 0;
+       l = myrpt->links.next;
+       while(l && (l != &myrpt->links)){
+               if(numoflinks >= MAX_STAT_LINKS){
+                       ast_log(LOG_WARNING,
+                       "maximum number of links exceeds %d in rpt_do_stats()!",MAX_STAT_LINKS);
+                       break;
                }
                }
+               //if (l->name[0] == '0'){ /* Skip '0' nodes */
+               //      reverse_patch_state = "UP";
+               //      l = l->next;
+               //      continue;
+               //}
+               numoflinks++;
+        
+               l = l->next;
        }
        }
+       ast_log(LOG_NOTICE, "numoflinks=%i\n",numoflinks);
+       return numoflinks;
+}
+/*
+ * Retrieve a memory channel
+ * Return 0 if sucessful,
+ * -1 if channel not found,
+ *  1 if parse error
+ */
+static int retreive_memory(struct rpt *myrpt, char *memory)
+{
+       char tmp[30], *s, *s1, *val;
 
 
-       /* If these aren't specified, copy them from the functions property. */
-       if (ast_strlen_zero(rpt_vars[n].p.link_functions))
-               ast_copy_string(rpt_vars[n].p.link_functions, rpt_vars[n].p.functions, sizeof(rpt_vars[n].p.link_functions));
-
-       rpt_vars[n].longestnode = 0;
-       for (vp = ast_variable_browse(cfg, rpt_vars[n].p.nodes); vp; vp = vp->next) {
-               if ((j = strlen(vp->name)) > rpt_vars[n].longestnode)
-                       rpt_vars[n].longestnode = j;
-       }
-
-       /*
-       * For this repeater, Determine the length of the longest function 
-       */
-       rpt_vars[n].longestfunc = 0;
-       for (vp = ast_variable_browse(cfg, rpt_vars[n].p.functions); vp; vp = vp->next) {
-               if ((j = strlen(vp->name)) > rpt_vars[n].longestfunc)
-                       rpt_vars[n].longestfunc = j;
-       }
-
-       rpt_vars[n].link_longestfunc = 0;
-       for (vp = ast_variable_browse(cfg, rpt_vars[n].p.link_functions); vp; vp = vp->next) {
-               if ((j = strlen(vp->name)) > rpt_vars[n].link_longestfunc)
-                       rpt_vars[n].link_longestfunc = j;
-       }
-
-       rpt_vars[n].phone_longestfunc = 0;
-       for (vp = ast_variable_browse(cfg, rpt_vars[n].p.phone_functions); vp; vp = vp->next) {
-               if ((j = strlen(vp->name)) > rpt_vars[n].phone_longestfunc)
-                       rpt_vars[n].phone_longestfunc = j;
-       }
+       if (debug)ast_log(LOG_NOTICE, "memory=%s block=%s\n",memory,myrpt->p.memory);
 
 
-       rpt_vars[n].dphone_longestfunc = 0;
-       for (vp = ast_variable_browse(cfg, rpt_vars[n].p.dphone_functions); vp; vp = vp->next) {
-               if ((j = strlen(vp->name)) > rpt_vars[n].dphone_longestfunc)
-                       rpt_vars[n].dphone_longestfunc = j;
-       }
+       val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.memory, memory);
+       if (!val){
+               return -1;
+       }                       
+       strncpy(tmp,val,sizeof(tmp) - 1);
+       tmp[sizeof(tmp)-1] = 0;
 
 
-       rpt_vars[n].macro_longest = 1;
-       for (vp = ast_variable_browse(cfg, rpt_vars[n].p.macro); vp; vp = vp->next) {
-               if ((j = strlen(vp->name)) > rpt_vars[n].macro_longest)
+       s = strchr(tmp,',');
+       if (!s)
+               return 1; 
+       *s++ = 0;
+       s1 = strchr(s,',');
+       if (!s1)
+               return 1;
+       *s1++ = 0;
+       strncpy(myrpt->freq, tmp, sizeof(myrpt->freq) - 1);
+       strncpy(myrpt->rxpl, s, sizeof(myrpt->rxpl) - 1);
+       strncpy(myrpt->txpl, s, sizeof(myrpt->rxpl) - 1);
+       myrpt->remmode = REM_MODE_FM;
+       myrpt->offset = REM_SIMPLEX;
+       myrpt->powerlevel = REM_MEDPWR;
+       myrpt->txplon = myrpt->rxplon = 0;
+       while(*s1){
+               switch(*s1++){
+                       case 'A':
+                       case 'a':
+                               strcpy(myrpt->rxpl, "100.0");
+                               strcpy(myrpt->txpl, "100.0");
+                               myrpt->remmode = REM_MODE_AM;   
+                               break;
+                       case 'B':
+                       case 'b':
+                               strcpy(myrpt->rxpl, "100.0");
+                               strcpy(myrpt->txpl, "100.0");
+                               myrpt->remmode = REM_MODE_LSB;
+                               break;
+                       case 'F':
+                               myrpt->remmode = REM_MODE_FM;
+                               break;
+                       case 'L':
+                       case 'l':
+                               myrpt->powerlevel = REM_LOWPWR;
+                               break;                                  
+                       case 'H':
+                       case 'h':
+                               myrpt->powerlevel = REM_HIPWR;
+                               break;
+                                       
+                       case 'M':
+                       case 'm':
+                               myrpt->powerlevel = REM_MEDPWR;
+                               break;
+                                               
+                       case '-':
+                               myrpt->offset = REM_MINUS;
+                               break;
+                                               
+                       case '+':
+                               myrpt->offset = REM_PLUS;
+                               break;
+                                               
+                       case 'S':
+                       case 's':
+                               myrpt->offset = REM_SIMPLEX;
+                               break;
+                                               
+                       case 'T':
+                       case 't':
+                               myrpt->txplon = 1;
+                               break;
+                                               
+                       case 'R':
+                       case 'r':
+                               myrpt->rxplon = 1;
+                               break;
+
+                       case 'U':
+                       case 'u':
+                               strcpy(myrpt->rxpl, "100.0");
+                               strcpy(myrpt->txpl, "100.0");
+                               myrpt->remmode = REM_MODE_USB;
+                               break;
+                       default:
+                               return 1;
+               }
+       }
+       return 0;
+}
+/*
+
+*/
+static void birdbath(struct rpt *myrpt)
+{
+       struct rpt_tele *telem;
+       if(debug > 2)
+               ast_log(LOG_NOTICE, "birdbath!!");
+       rpt_mutex_lock(&myrpt->lock);
+       telem = myrpt->tele.next;
+       while(telem != &myrpt->tele)
+       {
+               if (telem->mode == PARROT) ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
+               telem = telem->next;
+       }
+       rpt_mutex_unlock(&myrpt->lock);
+}
+
+static void do_dtmf_phone(struct rpt *myrpt, struct rpt_link *mylink, char c)
+{
+struct        rpt_link *l;
+
+       l = myrpt->links.next;
+       /* go thru all the links */
+       while(l != &myrpt->links)
+       {
+               if (!l->phonemode)
+               {
+                       l = l->next;
+                       continue;
+               }
+               /* dont send to self */
+               if (mylink && (l == mylink))
+               {
+                       l = l->next;
+                       continue;
+               }
+#ifdef NEW_ASTERISK
+               if (l->chan) ast_senddigit(l->chan,c,0);
+#else
+               if (l->chan) ast_senddigit(l->chan,c);
+#endif
+               l = l->next;
+       }
+       return;
+}
+
+/* node logging function */
+static void donodelog(struct rpt *myrpt,char *str)
+{
+struct nodelog *nodep;
+char   datestr[100];
+
+       if (!myrpt->p.archivedir) return;
+       nodep = (struct nodelog *)ast_malloc(sizeof(struct nodelog));
+       if (nodep == NULL)
+       {
+               ast_log(LOG_ERROR,"Cannot get memory for node log");
+               return;
+       }
+       time(&nodep->timestamp);
+       strncpy(nodep->archivedir,myrpt->p.archivedir,
+               sizeof(nodep->archivedir) - 1);
+       strftime(datestr,sizeof(datestr) - 1,"%Y%m%d%H%M%S",
+               localtime(&nodep->timestamp));
+       snprintf(nodep->str,sizeof(nodep->str) - 1,"%s %s,%s\n",
+               myrpt->name,datestr,str);
+       ast_mutex_lock(&nodeloglock);
+       insque((struct qelem *) nodep, (struct qelem *) nodelog.prev);
+       ast_mutex_unlock(&nodeloglock);
+}
+
+/* must be called locked */
+static void do_dtmf_local(struct rpt *myrpt, char c)
+{
+int    i;
+char   digit;
+static const char* dtmf_tones[] = {
+       "!941+1336/200,!0/200", /* 0 */
+       "!697+1209/200,!0/200", /* 1 */
+       "!697+1336/200,!0/200", /* 2 */
+       "!697+1477/200,!0/200", /* 3 */
+       "!770+1209/200,!0/200", /* 4 */
+       "!770+1336/200,!0/200", /* 5 */
+       "!770+1477/200,!0/200", /* 6 */
+       "!852+1209/200,!0/200", /* 7 */
+       "!852+1336/200,!0/200", /* 8 */
+       "!852+1477/200,!0/200", /* 9 */
+       "!697+1633/200,!0/200", /* A */
+       "!770+1633/200,!0/200", /* B */
+       "!852+1633/200,!0/200", /* C */
+       "!941+1633/200,!0/200", /* D */
+       "!941+1209/200,!0/200", /* * */
+       "!941+1477/200,!0/200" };       /* # */
+
+
+       if (c)
+       {
+               snprintf(myrpt->dtmf_local_str + strlen(myrpt->dtmf_local_str),sizeof(myrpt->dtmf_local_str) - 1,"%c",c);
+               if (!myrpt->dtmf_local_timer) 
+                        myrpt->dtmf_local_timer = DTMF_LOCAL_STARTTIME;
+       }
+       /* if at timeout */
+       if (myrpt->dtmf_local_timer == 1)
+       {
+               if(debug > 6)
+                       ast_log(LOG_NOTICE,"time out dtmf_local_timer=%i\n",myrpt->dtmf_local_timer);
+
+               /* if anything in the string */
+               if (myrpt->dtmf_local_str[0])
+               {
+                       digit = myrpt->dtmf_local_str[0];
+                       myrpt->dtmf_local_str[0] = 0;
+                       for(i = 1; myrpt->dtmf_local_str[i]; i++)
+                       {
+                               myrpt->dtmf_local_str[i - 1] =
+                                       myrpt->dtmf_local_str[i];
+                       }
+                       myrpt->dtmf_local_str[i - 1] = 0;
+                       myrpt->dtmf_local_timer = DTMF_LOCAL_TIME;
+                       rpt_mutex_unlock(&myrpt->lock);
+                       if (digit >= '0' && digit <='9')
+                               ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[digit-'0'], 0);
+                       else if (digit >= 'A' && digit <= 'D')
+                               ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[digit-'A'+10], 0);
+                       else if (digit == '*')
+                               ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[14], 0);
+                       else if (digit == '#')
+                               ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[15], 0);
+                       else {
+                               /* not handled */
+                               ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, myrpt->txchannel->name);
+                       }
+                       rpt_mutex_lock(&myrpt->lock);
+               }
+               else
+               {
+                       myrpt->dtmf_local_timer = 0;
+               }
+       }
+}
+
+static int setdtr(int fd, int enable)
+{
+struct termios mode;
+
+       if (fd < 0) return -1;
+       if (tcgetattr(fd, &mode)) {
+               ast_log(LOG_WARNING, "Unable to get serial parameters for dtr: %s\n", strerror(errno));
+               return -1;
+       }
+       if (enable)
+       {
+               cfsetspeed(&mode, B9600);
+       }
+       else
+       {
+               cfsetspeed(&mode, B0);
+               usleep(100000);
+       }
+       if (tcsetattr(fd, TCSADRAIN, &mode)) {
+               ast_log(LOG_WARNING, "Unable to set serial parameters for dtr: %s\n", strerror(errno));
+               return -1;
+       }
+       if (enable) usleep(100000);
+       return 0;
+}
+
+static int openserial(struct rpt *myrpt,char *fname)
+{
+       struct termios mode;
+       int fd;
+
+       fd = open(fname,O_RDWR);
+       if (fd == -1)
+       {
+               ast_log(LOG_WARNING,"Cannot open serial port %s\n",fname);
+               return -1;
+       }
+       memset(&mode, 0, sizeof(mode));
+       if (tcgetattr(fd, &mode)) {
+               ast_log(LOG_WARNING, "Unable to get serial parameters on %s: %s\n", fname, strerror(errno));
+               return -1;
+       }
+#ifndef        SOLARIS
+       cfmakeraw(&mode);
+#else
+        mode.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
+                        |INLCR|IGNCR|ICRNL|IXON);
+        mode.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
+        mode.c_cflag &= ~(CSIZE|PARENB|CRTSCTS);
+        mode.c_cflag |= CS8;
+       mode.c_cc[VTIME] = 3;
+       mode.c_cc[VMIN] = 1; 
+#endif
+
+       cfsetispeed(&mode, B9600);
+       cfsetospeed(&mode, B9600);
+       if (tcsetattr(fd, TCSANOW, &mode)) 
+               ast_log(LOG_WARNING, "Unable to set serial parameters on %s: %s\n", fname, strerror(errno));
+       if(!strcmp(myrpt->remoterig, remote_rig_kenwood)) setdtr(fd,0); 
+       usleep(100000);
+       if (debug)ast_log(LOG_NOTICE,"Opened serial port %s\n",fname);
+       return(fd);     
+}
+
+static void mdc1200_notify(struct rpt *myrpt,char *fromnode, unsigned int unit)
+{
+       if (!fromnode)
+       {
+               ast_verbose("Got MDC-1200 ID %04X from local system (%s)\n",
+                       unit,myrpt->name);
+       }
+       else
+       {
+               ast_verbose("Got MDC-1200 ID %04X from node %s (%s)\n",
+                       unit,fromnode,myrpt->name);
+       }
+}
+
+#ifdef _MDC_DECODE_H_
+
+static void mdc1200_send(struct rpt *myrpt, unsigned int unit)
+{
+struct rpt_link *l;
+struct ast_frame wf;
+char   str[200];
+
+
+       sprintf(str,"I %s %04X",myrpt->name,unit);
+
+       wf.frametype = AST_FRAME_TEXT;
+       wf.subclass = 0;
+       wf.offset = 0;
+       wf.mallocd = 0;
+       wf.datalen = strlen(str) + 1;
+       wf.samples = 0;
+
+
+       l = myrpt->links.next;
+       /* otherwise, send it to all of em */
+       while(l != &myrpt->links)
+       {
+               if (l->name[0] == '0') 
+               {
+                       l = l->next;
+                       continue;
+               }
+               wf.data = str;
+               if (l->chan) ast_write(l->chan,&wf); 
+               l = l->next;
+       }
+       return;
+}
+
+#endif
+
+static char func_xlat(struct rpt *myrpt,char c,struct rpt_xlat *xlat)
+{
+time_t now;
+int    gotone;
+
+       time(&now);
+       gotone = 0;
+       /* if too much time, reset the skate machine */
+       if ((now - xlat->lastone) > MAXXLATTIME)
+       {
+               xlat->funcindex = xlat->endindex = 0;
+       }
+       if (xlat->funccharseq[0] && (c == xlat->funccharseq[xlat->funcindex++]))
+       {
+               time(&xlat->lastone);
+               gotone = 1;
+               if (!xlat->funccharseq[xlat->funcindex])
+               {
+                       xlat->funcindex = xlat->endindex = 0;
+                       return(myrpt->p.funcchar);
+               }
+       } else xlat->funcindex = 0;
+       if (xlat->endcharseq[0] && (c == xlat->endcharseq[xlat->endindex++]))
+       {
+               time(&xlat->lastone);
+               gotone = 1;
+               if (!xlat->endcharseq[xlat->endindex])
+               {
+                       xlat->funcindex = xlat->endindex = 0;
+                       return(myrpt->p.endchar);
+               }
+       } else xlat->endindex = 0;
+       /* if in middle of decode seq, send nothing back */
+       if (gotone) return(0);
+       /* if no pass chars specified, return em all */
+       if (!xlat->passchars[0]) return(c);
+       /* if a "pass char", pass it */
+       if (strchr(xlat->passchars,c)) return(c);
+       return(0);
+}
+
+/*
+ * Return a pointer to the first non-whitespace character
+ */
+
+static char *eatwhite(char *s)
+{
+       while((*s == ' ') || (*s == 0x09)){ /* get rid of any leading white space */
+               if(!*s)
+                       break;
+               s++;
+       }
+       return s;
+}
+
+/*
+* Break up a delimited string into a table of substrings
+*
+* str - delimited string ( will be modified )
+* strp- list of pointers to substrings (this is built by this function), NULL will be placed at end of list
+* limit- maximum number of substrings to process
+*/
+       
+
+
+static int finddelim(char *str, char *strp[], int limit)
+{
+int     i,l,inquo;
+
+        inquo = 0;
+        i = 0;
+        strp[i++] = str;
+        if (!*str)
+           {
+                strp[0] = 0;
+                return(0);
+           }
+        for(l = 0; *str && (l < limit) ; str++)
+           {
+                if (*str == QUOTECHR)
+                   {
+                        if (inquo)
+                           {
+                                *str = 0;
+                                inquo = 0;
+                           }
+                        else
+                           {
+                                strp[i - 1] = str + 1;
+                                inquo = 1;
+                           }
+               }
+                if ((*str == DELIMCHR) && (!inquo))
+                {
+                        *str = 0;
+                       l++;
+                        strp[i++] = str + 1;
+                }
+           }
+        strp[i] = 0;
+        return(i);
+
+}
+/*
+       send asterisk frame text message on the current tx channel
+*/
+static int send_usb_txt(struct rpt *myrpt, char *txt) 
+{
+       struct ast_frame wf;
+       if (debug)ast_log(LOG_NOTICE, "send_usb_txt %s\n",txt);
+       wf.frametype = AST_FRAME_TEXT;
+       wf.subclass = 0;
+       wf.offset = 0;
+       wf.mallocd = 0;
+       wf.datalen = strlen(txt) + 1;
+       wf.data = txt;
+       wf.samples = 0;
+       ast_write(myrpt->txchannel,&wf); 
+       return 0;
+}
+/* must be called locked */
+static void __mklinklist(struct rpt *myrpt, struct rpt_link *mylink, char *buf)
+{
+struct rpt_link *l;
+char mode;
+int    i,spos;
+
+       buf[0] = 0; /* clear output buffer */
+       if (myrpt->remote) return;
+       /* go thru all links */
+       for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
+       {
+               /* if is not a real link, ignore it */
+               if (l->name[0] == '0') continue;
+               /* dont count our stuff */
+               if (l == mylink) continue;
+               if (mylink && (!strcmp(l->name,mylink->name))) continue;
+               /* figure out mode to report */
+               mode = 'T'; /* use Tranceive by default */
+               if (!l->mode) mode = 'R'; /* indicate RX for our mode */
+               if (!l->thisconnected)  mode = 'C'; /* indicate connecting */
+               spos = strlen(buf); /* current buf size (b4 we add our stuff) */
+               if (spos)
+               {
+                       strcat(buf,",");
+                       spos++;
+               }
+               /* add nodes into buffer */
+               if (l->linklist[0])
+               {
+                       snprintf(buf + spos,MAXLINKLIST - spos,
+                               "%c%s,%s",mode,l->name,l->linklist);
+               }
+               else /* if no nodes, add this node into buffer */
+               {
+                       snprintf(buf + spos,MAXLINKLIST - spos,
+                               "%c%s",mode,l->name);
+               }
+               /* if we are in tranceive mode, let all modes stand */
+               if (mode == 'T') continue;
+               /* downgrade everyone on this node if appropriate */
+               for(i = spos; buf[i]; i++)
+               {
+                       if (buf[i] == 'T') buf[i] = mode;
+                       if ((buf[i] == 'R') && (mode == 'C')) buf[i] = mode;
+               }
+       }
+       return;
+}
+
+/* must be called locked */
+static void __kickshort(struct rpt *myrpt)
+{
+struct rpt_link *l;
+
+       for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
+       {
+               /* if is not a real link, ignore it */
+               if (l->name[0] == '0') continue;
+               l->linklisttimer = LINKLISTSHORTTIME;
+       }
+       myrpt->linkposttimer = LINKPOSTSHORTTIME;
+       return;
+}
+
+static void statpost(struct rpt *myrpt,char *pairs)
+{
+char *str,*astr;
+char *astrs[100];
+int    n,pid;
+time_t now;
+unsigned int seq;
+
+       if (!myrpt->p.statpost_url) return;
+       str = ast_malloc(strlen(pairs) + strlen(myrpt->p.statpost_url) + 200);
+       astr = ast_strdup(myrpt->p.statpost_program);
+       if ((!str) || (!astr)) return;
+       n = finddelim(astr,astrs,100);
+       if (n < 1) return;
+       ast_mutex_lock(&myrpt->statpost_lock);
+       seq = ++myrpt->statpost_seqno;
+       ast_mutex_unlock(&myrpt->statpost_lock);
+       astrs[n++] = str;
+       astrs[n] = NULL;
+       time(&now);
+       sprintf(str,"%s?node=%s&time=%u&seqno=%u",myrpt->p.statpost_url,
+               myrpt->name,(unsigned int) now,seq);
+       if (pairs) sprintf(str + strlen(str),"&%s",pairs);
+       if (!(pid = fork()))
+       {
+               execv(astrs[0],astrs);
+               ast_log(LOG_ERROR, "exec of %s failed.\n", astrs[0]);
+               perror("asterisk");
+               exit(0);
+       }
+       ast_free(astr);
+       ast_free(str);
+       return;
+}
+
+static char *node_lookup(struct rpt *myrpt,char *digitbuf)
+{
+
+char *val;
+int longestnode,j;
+struct stat mystat;
+static time_t last = 0;
+static struct ast_config *ourcfg = NULL;
+struct ast_variable *vp;
+
+       /* try to look it up locally first */
+       val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.nodes, digitbuf);
+       if (val) return(val);
+       ast_mutex_lock(&nodelookuplock);
+       /* if file does not exist */
+       if (stat(myrpt->p.extnodefile,&mystat) == -1)
+       {
+               if (ourcfg) ast_config_destroy(ourcfg);
+               ourcfg = NULL;
+               ast_mutex_unlock(&nodelookuplock);
+               return(NULL);
+       }
+       /* if we need to reload */
+       if (mystat.st_mtime > last)
+       {
+               if (ourcfg) ast_config_destroy(ourcfg);
+#ifdef NEW_ASTERISK
+               ourcfg = ast_config_load(myrpt->p.extnodefile,config_flags);
+#else
+               ourcfg = ast_config_load(myrpt->p.extnodefile);
+#endif
+               /* if file not there, just bail */
+               if (!ourcfg)
+               {
+                       ast_mutex_unlock(&nodelookuplock);
+                       return(NULL);
+               }
+               /* reset "last" time */
+               last = mystat.st_mtime;
+
+               /* determine longest node length again */               
+               longestnode = 0;
+               vp = ast_variable_browse(myrpt->cfg, myrpt->p.nodes);
+               while(vp){
+                       j = strlen(vp->name);
+                       if (j > longestnode)
+                               longestnode = j;
+                       vp = vp->next;
+               }
+
+               vp = ast_variable_browse(ourcfg, myrpt->p.extnodes);
+               while(vp){
+                       j = strlen(vp->name);
+                       if (j > longestnode)
+                               longestnode = j;
+                       vp = vp->next;
+               }
+
+               myrpt->longestnode = longestnode;
+       }
+       val = NULL;
+       if (ourcfg)
+               val = (char *) ast_variable_retrieve(ourcfg, myrpt->p.extnodes, digitbuf);
+       ast_mutex_unlock(&nodelookuplock);
+       return(val);
+}
+
+/*
+* Match a keyword in a list, and return index of string plus 1 if there was a match,* else return 0.
+* If param is passed in non-null, then it will be set to the first character past the match
+*/
+
+static int matchkeyword(char *string, char **param, char *keywords[])
+{
+int    i,ls;
+       for( i = 0 ; keywords[i] ; i++){
+               ls = strlen(keywords[i]);
+               if(!ls){
+                       *param = NULL;
+                       return 0;
+               }
+               if(!strncmp(string, keywords[i], ls)){
+                       if(param)
+                               *param = string + ls;
+                       return i + 1; 
+               }
+       }
+       *param = NULL;
+       return 0;
+}
+
+/*
+* Skip characters in string which are in charlist, and return a pointer to the
+* first non-matching character
+*/
+
+static char *skipchars(char *string, char *charlist)
+{
+int i; 
+       while(*string){
+               for(i = 0; charlist[i] ; i++){
+                       if(*string == charlist[i]){
+                               string++;
+                               break;
+                       }
+               }
+               if(!charlist[i])
+                       return string;
+       }
+       return string;
+}      
+                                       
+
+
+static int myatoi(char *str)
+{
+int    ret;
+
+       if (str == NULL) return -1;
+       /* leave this %i alone, non-base-10 input is useful here */
+       if (sscanf(str,"%i",&ret) != 1) return -1;
+       return ret;
+}
+
+static int mycompar(const void *a, const void *b)
+{
+char   **x = (char **) a;
+char   **y = (char **) b;
+int    xoff,yoff;
+
+       if ((**x < '0') || (**x > '9')) xoff = 1; else xoff = 0;
+       if ((**y < '0') || (**y > '9')) yoff = 1; else yoff = 0;
+       return(strcmp((*x) + xoff,(*y) + yoff));
+}
+
+static int topcompar(const void *a, const void *b)
+{
+struct rpt_topkey *x = (struct rpt_topkey *) a;
+struct rpt_topkey *y = (struct rpt_topkey *) b;
+
+       return(x->timesince - y->timesince);
+}
+
+#ifdef __RPT_NOTCH
+
+/* rpt filter routine */
+static void rpt_filter(struct rpt *myrpt, volatile short *buf, int len)
+{
+int    i,j;
+struct rptfilter *f;
+
+       for(i = 0; i < len; i++)
+       {
+               for(j = 0; j < MAXFILTERS; j++)
+               {
+                       f = &myrpt->filters[j];
+                       if (!*f->desc) continue;
+                       f->x0 = f->x1; f->x1 = f->x2;
+                       f->x2 = ((float)buf[i]) / f->gain;
+                       f->y0 = f->y1; f->y1 = f->y2;
+                       f->y2 =   (f->x0 + f->x2) +   f->const0 * f->x1
+                                    + (f->const1 * f->y0) + (f->const2 * f->y1);
+                       buf[i] = (short)f->y2;
+               }
+       }
+}
+
+#endif
+
+
+/*
+ Get the time for the machine's time zone
+ Note: Asterisk requires a copy of localtime
+ in the /etc directory for this to work properly.
+ If /etc/localtime is not present, you will get
+ GMT time! This is especially important on systems
+ running embedded linux distributions as they don't usually
+ have support for locales. 
+
+ If OLD_ASTERISK is defined, then the older localtime_r
+ function will be used. The /etc/localtime file is not
+ required in this case. This provides backward compatibility
+ with Asterisk 1.2 systems.
+
+*/
+
+#ifdef NEW_ASTERISK
+static void rpt_localtime( time_t * t, struct ast_tm *lt)
+{
+struct timeval tv;
+
+       tv.tv_sec = *t;
+       tv.tv_usec = 0;
+       ast_localtime(&tv, lt, NULL);
+
+}
+
+#else
+static void rpt_localtime( time_t * t, struct tm *lt)
+{
+#ifdef OLD_ASTERISK
+       localtime_r(t, lt);
+#else
+       ast_localtime(t, lt, NULL);
+#endif
+}
+#endif
+
+
+/* Retrieve an int from a config file */
+                                                                                
+static int retrieve_astcfgint(struct rpt *myrpt,char *category, char *name, int min, int max, int defl)
+{
+        char *var;
+        int ret;
+       char include_zero = 0;
+
+       if(min < 0){ /* If min is negative, this means include 0 as a valid entry */
+               min = -min;
+               include_zero = 1;
+       }           
+                                                                     
+        var = (char *) ast_variable_retrieve(myrpt->cfg, category, name);
+        if(var){
+                ret = myatoi(var);
+               if(include_zero && !ret)
+                       return 0;
+                if(ret < min)
+                        ret = min;
+                if(ret > max)
+                        ret = max;
+        }
+        else
+                ret = defl;
+        return ret;
+}
+
+
+static void load_rpt_vars(int n,int init)
+{
+char *this,*val;
+int    i,j,longestnode;
+struct ast_variable *vp;
+struct ast_config *cfg;
+char *strs[100];
+char s1[256];
+static char *cs_keywords[] = {"rptena","rptdis","apena","apdis","lnkena","lnkdis","totena","totdis","skena","skdis",
+                               "ufena","ufdis","atena","atdis",NULL};
+
+       if (option_verbose > 2)
+               ast_verbose(VERBOSE_PREFIX_3 "%s config for repeater %s\n",
+                       (init) ? "Loading initial" : "Re-Loading",rpt_vars[n].name);
+       ast_mutex_lock(&rpt_vars[n].lock);
+       if (rpt_vars[n].cfg) ast_config_destroy(rpt_vars[n].cfg);
+#ifdef NEW_ASTERISK
+       cfg = ast_config_load("rpt.conf",config_flags);
+#else
+       cfg = ast_config_load("rpt.conf");
+#endif
+       if (!cfg) {
+               ast_mutex_unlock(&rpt_vars[n].lock);
+               ast_log(LOG_NOTICE, "Unable to open radio repeater configuration rpt.conf.  Radio Repeater disabled.\n");
+               pthread_exit(NULL);
+       }
+       rpt_vars[n].cfg = cfg; 
+       this = rpt_vars[n].name;
+       memset(&rpt_vars[n].p,0,sizeof(rpt_vars[n].p));
+       if (init)
+       {
+               char *cp;
+               int savearea = (char *)&rpt_vars[n].p - (char *)&rpt_vars[n];
+
+               cp = (char *) &rpt_vars[n].p;
+               memset(cp + sizeof(rpt_vars[n].p),0,
+                       sizeof(rpt_vars[n]) - (sizeof(rpt_vars[n].p) + savearea));
+               rpt_vars[n].tele.next = &rpt_vars[n].tele;
+               rpt_vars[n].tele.prev = &rpt_vars[n].tele;
+               rpt_vars[n].rpt_thread = AST_PTHREADT_NULL;
+               rpt_vars[n].tailmessagen = 0;
+       }
+#ifdef __RPT_NOTCH
+       /* zot out filters stuff */
+       memset(&rpt_vars[n].filters,0,sizeof(rpt_vars[n].filters));
+#endif
+       val = (char *) ast_variable_retrieve(cfg,this,"context");
+       if (val) rpt_vars[n].p.ourcontext = val;
+       else rpt_vars[n].p.ourcontext = this;
+       val = (char *) ast_variable_retrieve(cfg,this,"callerid");
+       if (val) rpt_vars[n].p.ourcallerid = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"accountcode");
+       if (val) rpt_vars[n].p.acctcode = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"idrecording");
+       if (val) rpt_vars[n].p.ident = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"hangtime");
+       if (val) rpt_vars[n].p.hangtime = atoi(val);
+               else rpt_vars[n].p.hangtime = HANGTIME;
+       val = (char *) ast_variable_retrieve(cfg,this,"althangtime");
+       if (val) rpt_vars[n].p.althangtime = atoi(val);
+               else rpt_vars[n].p.althangtime = HANGTIME;
+       val = (char *) ast_variable_retrieve(cfg,this,"totime");
+       if (val) rpt_vars[n].p.totime = atoi(val);
+               else rpt_vars[n].p.totime = TOTIME;
+       val = (char *) ast_variable_retrieve(cfg,this,"voxtimeout");
+       if (val) rpt_vars[n].p.voxtimeout_ms = atoi(val);
+               else rpt_vars[n].p.voxtimeout_ms = VOX_TIMEOUT_MS;
+       val = (char *) ast_variable_retrieve(cfg,this,"voxrecover");
+       if (val) rpt_vars[n].p.voxrecover_ms = atoi(val);
+               else rpt_vars[n].p.voxrecover_ms = VOX_RECOVER_MS;
+       val = (char *) ast_variable_retrieve(cfg,this,"simplexpatchdelay");
+       if (val) rpt_vars[n].p.simplexpatchdelay = atoi(val);
+               else rpt_vars[n].p.simplexpatchdelay = SIMPLEX_PATCH_DELAY;
+       val = (char *) ast_variable_retrieve(cfg,this,"simplexphonedelay");
+       if (val) rpt_vars[n].p.simplexphonedelay = atoi(val);
+               else rpt_vars[n].p.simplexphonedelay = SIMPLEX_PHONE_DELAY;
+       val = (char *) ast_variable_retrieve(cfg,this,"statpost_program");
+       if (val) rpt_vars[n].p.statpost_program = val;
+               else rpt_vars[n].p.statpost_program = STATPOST_PROGRAM;
+       rpt_vars[n].p.statpost_url = 
+               (char *) ast_variable_retrieve(cfg,this,"statpost_url");
+       rpt_vars[n].p.tailmessagetime = retrieve_astcfgint(&rpt_vars[n],this, "tailmessagetime", 0, 2400000, 0);                
+       rpt_vars[n].p.tailsquashedtime = retrieve_astcfgint(&rpt_vars[n],this, "tailsquashedtime", 0, 2400000, 0);              
+       rpt_vars[n].p.duplex = retrieve_astcfgint(&rpt_vars[n],this,"duplex",0,4,2);
+       rpt_vars[n].p.idtime = retrieve_astcfgint(&rpt_vars[n],this, "idtime", -60000, 2400000, IDTIME);        /* Enforce a min max including zero */
+       rpt_vars[n].p.politeid = retrieve_astcfgint(&rpt_vars[n],this, "politeid", 30000, 300000, POLITEID); /* Enforce a min max */
+       val = (char *) ast_variable_retrieve(cfg,this,"tonezone");
+       if (val) rpt_vars[n].p.tonezone = val;
+       rpt_vars[n].p.tailmessages[0] = 0;
+       rpt_vars[n].p.tailmessagemax = 0;
+       val = (char *) ast_variable_retrieve(cfg,this,"tailmessagelist");
+       if (val) rpt_vars[n].p.tailmessagemax = finddelim(val, rpt_vars[n].p.tailmessages, 500);
+       val = (char *) ast_variable_retrieve(cfg,this,"memory");
+       if (!val) val = MEMORY;
+       rpt_vars[n].p.memory = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"macro");
+       if (!val) val = MACRO;
+       rpt_vars[n].p.macro = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"tonemacro");
+       if (!val) val = TONEMACRO;
+       rpt_vars[n].p.tonemacro = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"startup_macro");
+       if (val) rpt_vars[n].p.startupmacro = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"iobase");
+       /* do not use atoi() here, we need to be able to have
+               the input specified in hex or decimal so we use
+               sscanf with a %i */
+       if ((!val) || (sscanf(val,"%i",&rpt_vars[n].p.iobase) != 1))
+               rpt_vars[n].p.iobase = DEFAULT_IOBASE;
+       val = (char *) ast_variable_retrieve(cfg,this,"ioport");
+       rpt_vars[n].p.ioport = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"functions");
+       if (!val)
+               {
+                       val = FUNCTIONS;
+                       rpt_vars[n].p.simple = 1;
+               } 
+       rpt_vars[n].p.functions = val;
+       val =  (char *) ast_variable_retrieve(cfg,this,"link_functions");
+       if (val) rpt_vars[n].p.link_functions = val;
+       else 
+               rpt_vars[n].p.link_functions = rpt_vars[n].p.functions;
+       val = (char *) ast_variable_retrieve(cfg,this,"phone_functions");
+       if (val) rpt_vars[n].p.phone_functions = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"dphone_functions");
+       if (val) rpt_vars[n].p.dphone_functions = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"alt_functions");
+       if (val) rpt_vars[n].p.alt_functions = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"funcchar");
+       if (!val) rpt_vars[n].p.funcchar = FUNCCHAR; else 
+               rpt_vars[n].p.funcchar = *val;          
+       val = (char *) ast_variable_retrieve(cfg,this,"endchar");
+       if (!val) rpt_vars[n].p.endchar = ENDCHAR; else 
+               rpt_vars[n].p.endchar = *val;           
+       val = (char *) ast_variable_retrieve(cfg,this,"nobusyout");
+       if (val) rpt_vars[n].p.nobusyout = ast_true(val);
+       val = (char *) ast_variable_retrieve(cfg,this,"notelemtx");
+       if (val) rpt_vars[n].p.notelemtx = ast_true(val);
+       val = (char *) ast_variable_retrieve(cfg,this,"propagate_dtmf");
+       if (val) rpt_vars[n].p.propagate_dtmf = ast_true(val);
+       val = (char *) ast_variable_retrieve(cfg,this,"propagate_phonedtmf");
+       if (val) rpt_vars[n].p.propagate_phonedtmf = ast_true(val);
+       val = (char *) ast_variable_retrieve(cfg,this,"linktolink");
+       if (val) rpt_vars[n].p.linktolink = ast_true(val);
+       val = (char *) ast_variable_retrieve(cfg,this,"nodes");
+       if (!val) val = NODES;
+       rpt_vars[n].p.nodes = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"extnodes");
+       if (!val) val = EXTNODES;
+       rpt_vars[n].p.extnodes = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"extnodefile");
+       if (!val) val = EXTNODEFILE;
+       rpt_vars[n].p.extnodefile = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"archivedir");
+       if (val) rpt_vars[n].p.archivedir = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"authlevel");
+       if (val) rpt_vars[n].p.authlevel = atoi(val); 
+       else rpt_vars[n].p.authlevel = 0;
+       val = (char *) ast_variable_retrieve(cfg,this,"parrot");
+       if (val) rpt_vars[n].p.parrotmode = ast_true(val) * 2;
+       else rpt_vars[n].p.parrotmode = 0;
+       val = (char *) ast_variable_retrieve(cfg,this,"parrottime");
+       if (val) rpt_vars[n].p.parrottime = atoi(val); 
+       else rpt_vars[n].p.parrottime = PARROTTIME;
+       val = (char *) ast_variable_retrieve(cfg,this,"rptnode");
+       rpt_vars[n].p.rptnode = val;
+       val = (char *) ast_variable_retrieve(cfg,this,"mars");
+       if (val) rpt_vars[n].p.remote_mars = atoi(val); 
+       else rpt_vars[n].p.remote_mars = 0;
+       val = (char *) ast_variable_retrieve(cfg,this,"monminblocks");
+       if (val) rpt_vars[n].p.monminblocks = atol(val); 
+       else rpt_vars[n].p.monminblocks = DEFAULT_MONITOR_MIN_DISK_BLOCKS;
+       val = (char *) ast_variable_retrieve(cfg,this,"remote_inact_timeout");
+       if (val) rpt_vars[n].p.remoteinacttimeout = atoi(val); 
+       else rpt_vars[n].p.remoteinacttimeout = DEFAULT_REMOTE_INACT_TIMEOUT;
+       val = (char *) ast_variable_retrieve(cfg,this,"civaddr");
+       if (val) rpt_vars[n].p.civaddr = atoi(val); 
+       else rpt_vars[n].p.civaddr = DEFAULT_CIV_ADDR;
+       val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout");
+       if (val) rpt_vars[n].p.remotetimeout = atoi(val); 
+       else rpt_vars[n].p.remotetimeout = DEFAULT_REMOTE_TIMEOUT;
+       val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout_warning");
+       if (val) rpt_vars[n].p.remotetimeoutwarning = atoi(val); 
+       else rpt_vars[n].p.remotetimeoutwarning = DEFAULT_REMOTE_TIMEOUT_WARNING;
+       val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout_warning_freq");
+       if (val) rpt_vars[n].p.remotetimeoutwarningfreq = atoi(val); 
+       else rpt_vars[n].p.remotetimeoutwarningfreq = DEFAULT_REMOTE_TIMEOUT_WARNING_FREQ;
+#ifdef __RPT_NOTCH
+       val = (char *) ast_variable_retrieve(cfg,this,"rxnotch");
+       if (val) {
+               i = finddelim(val,strs,MAXFILTERS * 2);
+               i &= ~1; /* force an even number, rounded down */
+               if (i >= 2) for(j = 0; j < i; j += 2)
+               {
+                       rpt_mknotch(atof(strs[j]),atof(strs[j + 1]),
+                         &rpt_vars[n].filters[j >> 1].gain,
+                           &rpt_vars[n].filters[j >> 1].const0,
+                               &rpt_vars[n].filters[j >> 1].const1,
+                                   &rpt_vars[n].filters[j >> 1].const2);
+                       sprintf(rpt_vars[n].filters[j >> 1].desc,"%s Hz, BW = %s",
+                               strs[j],strs[j + 1]);
+               }
+
+       }
+#endif
+       val = (char *) ast_variable_retrieve(cfg,this,"inxlat");
+       if (val) {
+               memset(&rpt_vars[n].p.inxlat,0,sizeof(struct rpt_xlat));
+               i = finddelim(val,strs,3);
+               if (i) strncpy(rpt_vars[n].p.inxlat.funccharseq,strs[0],MAXXLAT - 1);
+               if (i > 1) strncpy(rpt_vars[n].p.inxlat.endcharseq,strs[1],MAXXLAT - 1);
+               if (i > 2) strncpy(rpt_vars[n].p.inxlat.passchars,strs[2],MAXXLAT - 1);
+       }
+       val = (char *) ast_variable_retrieve(cfg,this,"outxlat");
+       if (val) {
+               memset(&rpt_vars[n].p.outxlat,0,sizeof(struct rpt_xlat));
+               i = finddelim(val,strs,3);
+               if (i) strncpy(rpt_vars[n].p.outxlat.funccharseq,strs[0],MAXXLAT - 1);
+               if (i > 1) strncpy(rpt_vars[n].p.outxlat.endcharseq,strs[1],MAXXLAT - 1);
+               if (i > 2) strncpy(rpt_vars[n].p.outxlat.passchars,strs[2],MAXXLAT - 1);
+       }
+       /* retreive the stanza name for the control states if there is one */
+       val = (char *) ast_variable_retrieve(cfg,this,"controlstates");
+       rpt_vars[n].p.csstanzaname = val;
+               
+       /* retreive the stanza name for the scheduler if there is one */
+       val = (char *) ast_variable_retrieve(cfg,this,"scheduler");
+       rpt_vars[n].p.skedstanzaname = val;
+
+       /* retreive the stanza name for the txlimits */
+       val = (char *) ast_variable_retrieve(cfg,this,"txlimits");
+       rpt_vars[n].p.txlimitsstanzaname = val;
+
+       longestnode = 0;
+
+       vp = ast_variable_browse(cfg, rpt_vars[n].p.nodes);
+               
+       while(vp){
+               j = strlen(vp->name);
+               if (j > longestnode)
+                       longestnode = j;
+               vp = vp->next;
+       }
+
+       rpt_vars[n].longestnode = longestnode;
+               
+       /*
+       * For this repeater, Determine the length of the longest function 
+       */
+       rpt_vars[n].longestfunc = 0;
+       vp = ast_variable_browse(cfg, rpt_vars[n].p.functions);
+       while(vp){
+               j = strlen(vp->name);
+               if (j > rpt_vars[n].longestfunc)
+                       rpt_vars[n].longestfunc = j;
+               vp = vp->next;
+       }
+       /*
+       * For this repeater, Determine the length of the longest function 
+       */
+       rpt_vars[n].link_longestfunc = 0;
+       vp = ast_variable_browse(cfg, rpt_vars[n].p.link_functions);
+       while(vp){
+               j = strlen(vp->name);
+               if (j > rpt_vars[n].link_longestfunc)
+                       rpt_vars[n].link_longestfunc = j;
+               vp = vp->next;
+       }
+       rpt_vars[n].phone_longestfunc = 0;
+       if (rpt_vars[n].p.phone_functions)
+       {
+               vp = ast_variable_browse(cfg, rpt_vars[n].p.phone_functions);
+               while(vp){
+                       j = strlen(vp->name);
+                       if (j > rpt_vars[n].phone_longestfunc)
+                               rpt_vars[n].phone_longestfunc = j;
+                       vp = vp->next;
+               }
+       }
+       rpt_vars[n].dphone_longestfunc = 0;
+       if (rpt_vars[n].p.dphone_functions)
+       {
+               vp = ast_variable_browse(cfg, rpt_vars[n].p.dphone_functions);
+               while(vp){
+                       j = strlen(vp->name);
+                       if (j > rpt_vars[n].dphone_longestfunc)
+                               rpt_vars[n].dphone_longestfunc = j;
+                       vp = vp->next;
+               }
+       }
+       rpt_vars[n].alt_longestfunc = 0;
+       if (rpt_vars[n].p.alt_functions)
+       {
+               vp = ast_variable_browse(cfg, rpt_vars[n].p.alt_functions);
+               while(vp){
+                       j = strlen(vp->name);
+                       if (j > rpt_vars[n].alt_longestfunc)
+                               rpt_vars[n].alt_longestfunc = j;
+                       vp = vp->next;
+               }
+       }
+       rpt_vars[n].macro_longest = 1;
+       vp = ast_variable_browse(cfg, rpt_vars[n].p.macro);
+       while(vp){
+               j = strlen(vp->name);
+               if (j > rpt_vars[n].macro_longest)
                        rpt_vars[n].macro_longest = j;
                        rpt_vars[n].macro_longest = j;
+               vp = vp->next;
        }
        }
+       
+       /* Browse for control states */
+       if(rpt_vars[n].p.csstanzaname)
+               vp = ast_variable_browse(cfg, rpt_vars[n].p.csstanzaname);
+       else
+               vp = NULL;
+       for( i = 0 ; vp && (i < MAX_SYSSTATES) ; i++){ /* Iterate over the number of control state lines in the stanza */
+               int k,nukw,statenum;
+               statenum=atoi(vp->name);
+               strncpy(s1, vp->value, 255);
+               s1[255] = 0;
+               nukw  = finddelim(s1,strs,32);
+               
+               for (k = 0 ; k < nukw ; k++){ /* for each user specified keyword */     
+                       for(j = 0 ; cs_keywords[j] != NULL ; j++){ /* try to match to one in our internal table */
+                               if(!strcmp(strs[k],cs_keywords[j])){
+                                       switch(j){
+                                               case 0: /* rptena */
+                                                       rpt_vars[n].p.s[statenum].txdisable = 0;
+                                                       break;
+                                               case 1: /* rptdis */
+                                                       rpt_vars[n].p.s[statenum].txdisable = 1;
+                                                       break;
+                       
+                                               case 2: /* apena */
+                                                       rpt_vars[n].p.s[statenum].autopatchdisable = 0;
+                                                       break;
 
 
-       rpt_vars[n].gosub_longest = 1;
-       for (vp = ast_variable_browse(cfg, rpt_vars[n].p.gosub); vp; vp = vp->next) {
-               if ((j = strlen(vp->name)) > rpt_vars[n].gosub_longest)
-                       rpt_vars[n].gosub_longest = j;
+                                               case 3: /* apdis */
+                                                       rpt_vars[n].p.s[statenum].autopatchdisable = 1;
+                                                       break;
+
+                                               case 4: /* lnkena */
+                                                       rpt_vars[n].p.s[statenum].linkfundisable = 0;
+                                                       break;
+       
+                                               case 5: /* lnkdis */
+                                                       rpt_vars[n].p.s[statenum].linkfundisable = 1;
+                                                       break;
+
+                                               case 6: /* totena */
+                                                       rpt_vars[n].p.s[statenum].totdisable = 0;
+                                                       break;
+                                       
+                                               case 7: /* totdis */
+                                                       rpt_vars[n].p.s[statenum].totdisable = 1;
+                                                       break;
+
+                                               case 8: /* skena */
+                                                       rpt_vars[n].p.s[statenum].schedulerdisable = 0;
+                                                       break;
+
+                                               case 9: /* skdis */
+                                                       rpt_vars[n].p.s[statenum].schedulerdisable = 1;
+                                                       break;
+
+                                               case 10: /* ufena */
+                                                       rpt_vars[n].p.s[statenum].userfundisable = 0;
+                                                       break;
+
+                                               case 11: /* ufdis */
+                                                       rpt_vars[n].p.s[statenum].userfundisable = 1;
+                                                       break;
+
+                                               case 12: /* atena */
+                                                       rpt_vars[n].p.s[statenum].alternatetail = 1;
+                                                       break;
+
+                                               case 13: /* atdis */
+                                                       rpt_vars[n].p.s[statenum].alternatetail = 0;
+                                                       break;
+                       
+                                               default:
+                                                       ast_log(LOG_WARNING,
+                                                               "Unhandled control state keyword %s", cs_keywords[i]);
+                                                       break;
+                                       }
+                               }
+                       }
+               }
+               vp = vp->next;
        }
        ast_mutex_unlock(&rpt_vars[n].lock);
 }
        }
        ast_mutex_unlock(&rpt_vars[n].lock);
 }
@@ -1074,113 +2616,87 @@ static void load_rpt_vars(int n, int init)
 /*
 * Enable or disable debug output at a given level at the console
 */
 /*
 * Enable or disable debug output at a given level at the console
 */
-static char *handle_cli_rpt_debug_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+                                                                                                                                 
+static int rpt_do_debug(int fd, int argc, char *argv[])
 {
        int newlevel;
 
 {
        int newlevel;
 
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "rpt debug level";
-               e->usage =
-                       "Usage: rpt debug level {0-7}\n"
-                       "       Enables debug messages in app_rpt\n";
-               return NULL;
-       case CLI_GENERATE:
-               return NULL;
-       }
-       if (a->argc != e->args)
-               return CLI_SHOWUSAGE;
-       newlevel = myatoi(a->argv[3]);
-       if ((newlevel < 0) || (newlevel > 7))
-               return CLI_SHOWUSAGE;
-       if (newlevel)
-               ast_cli(a->fd, "app_rpt Debugging enabled, previous level: %d, new level: %d\n", debug, newlevel);
-       else
-               ast_cli(a->fd, "app_rpt Debugging disabled\n");
-
-       debug = newlevel;
-
-       return CLI_SUCCESS;
+        if (argc != 4)
+                return RESULT_SHOWUSAGE;
+        newlevel = myatoi(argv[3]);
+        if((newlevel < 0) || (newlevel > 7))
+                return RESULT_SHOWUSAGE;
+        if(newlevel)
+                ast_cli(fd, "app_rpt Debugging enabled, previous level: %d, new level: %d\n", debug, newlevel);
+        else
+                ast_cli(fd, "app_rpt Debugging disabled\n");
+
+        debug = newlevel;                                                                                                                          
+        return RESULT_SUCCESS;
 }
 
 /*
 * Dump rpt struct debugging onto console
 */
 }
 
 /*
 * Dump rpt struct debugging onto console
 */
-static char *handle_cli_rpt_dump(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+                                                                                                                                 
+static int rpt_do_dump(int fd, int argc, char *argv[])
 {
        int i;
 
 {
        int i;
 
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "rpt dump";
-               e->usage =
-                       "Usage: rpt dump <nodename>\n"
-                       "       Dumps struct debug info to log\n";
-               return NULL;
-       case CLI_GENERATE:
-               return NULL;
-       }
-
-       if (a->argc != 3)
-               return CLI_SHOWUSAGE;
+        if (argc != 3)
+                return RESULT_SHOWUSAGE;
 
 
-       for (i = 0; i < nrpts; i++) {
-               if (!strcmp(a->argv[2], rpt_vars[i].name)) {
+       for(i = 0; i < nrpts; i++)
+       {
+               if (!strcmp(argv[2],rpt_vars[i].name))
+               {
                        rpt_vars[i].disgorgetime = time(NULL) + 10; /* Do it 10 seconds later */
                        rpt_vars[i].disgorgetime = time(NULL) + 10; /* Do it 10 seconds later */
-                       ast_cli(a->fd, "app_rpt struct dump requested for node %s\n", a->argv[2]);
-                       return CLI_SUCCESS;
+                       ast_cli(fd, "app_rpt struct dump requested for node %s\n",argv[2]);
+                       return RESULT_SUCCESS;
                }
        }
                }
        }
-       return CLI_FAILURE;
+       return RESULT_FAILURE;
 }
 
 /*
 * Dump statistics onto console
 */
 }
 
 /*
 * Dump statistics onto console
 */
-static char *handle_cli_rpt_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+
+static int rpt_do_stats(int fd, int argc, char *argv[])
 {
 {
-       int i, j;
+       int i,j,numoflinks;
        int dailytxtime, dailykerchunks;
        int dailytxtime, dailykerchunks;
+       time_t now;
        int totalkerchunks, dailykeyups, totalkeyups, timeouts;
        int totalexecdcommands, dailyexecdcommands, hours, minutes, seconds;
        int totalkerchunks, dailykeyups, totalkeyups, timeouts;
        int totalexecdcommands, dailyexecdcommands, hours, minutes, seconds;
+       int uptime;
        long long totaltxtime;
        long long totaltxtime;
-       struct rpt_link *l;
+       struct  rpt_link *l;
        char *listoflinks[MAX_STAT_LINKS];      
        char *listoflinks[MAX_STAT_LINKS];      
-       char *lastnodewhichkeyedusup, *lastdtmfcommand;
+       char *lastdtmfcommand,*parrot_ena;
        char *tot_state, *ider_state, *patch_state;
        char *tot_state, *ider_state, *patch_state;
-       char *reverse_patch_state, *enable_state, *input_signal, *called_number;
+       char *reverse_patch_state, *sys_ena, *tot_ena, *link_ena, *patch_ena;
+       char *sch_ena, *input_signal, *called_number, *user_funs, *tail_type;
        struct rpt *myrpt;
 
        static char *not_applicable = "N/A";
 
        struct rpt *myrpt;
 
        static char *not_applicable = "N/A";
 
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "rpt stats";
-               e->usage =
-                       "Usage: rpt stats <nodename>\n"
-                       "       Dumps node statistics to console\n";
-               return NULL;
-       case CLI_GENERATE:
-               return NULL;
-       }
-
-       if (a->argc != 3)
-               return CLI_SHOWUSAGE;
-
-       for (i = 0 ; i <= MAX_STAT_LINKS; i++)
-               listoflinks[i] = NULL;
+       if(argc != 3)
+               return RESULT_SHOWUSAGE;
 
        tot_state = ider_state = 
        patch_state = reverse_patch_state = 
 
        tot_state = ider_state = 
        patch_state = reverse_patch_state = 
-       input_signal = called_number = 
-       lastdtmfcommand = not_applicable;
+       input_signal = not_applicable;
+       called_number = lastdtmfcommand = NULL;
 
 
-       for (i = 0; i < nrpts; i++) {
-               if (!strcmp(a->argv[2], rpt_vars[i].name)) {
+       time(&now);
+       for(i = 0; i < nrpts; i++)
+       {
+               if (!strcmp(argv[2],rpt_vars[i].name)){
                        /* Make a copy of all stat variables while locked */
                        myrpt = &rpt_vars[i];
                        rpt_mutex_lock(&myrpt->lock); /* LOCK */
                        /* Make a copy of all stat variables while locked */
                        myrpt = &rpt_vars[i];
                        rpt_mutex_lock(&myrpt->lock); /* LOCK */
-
+                       uptime = (int)(now - starttime);
                        dailytxtime = myrpt->dailytxtime;
                        totaltxtime = myrpt->totaltxtime;
                        dailykeyups = myrpt->dailykeyups;
                        dailytxtime = myrpt->dailytxtime;
                        totaltxtime = myrpt->totaltxtime;
                        dailykeyups = myrpt->dailykeyups;
@@ -1193,293 +2709,555 @@ static char *handle_cli_rpt_stats(struct ast_cli_entry *e, int cmd, struct ast_c
 
                        /* Traverse the list of connected nodes */
                        reverse_patch_state = "DOWN";
 
                        /* Traverse the list of connected nodes */
                        reverse_patch_state = "DOWN";
-                       j = 0;
+                       numoflinks = 0;
                        l = myrpt->links.next;
                        l = myrpt->links.next;
-                       while (l != &myrpt->links) {
-                               if (l->name[0] == '0') { /* Skip '0' nodes */
+                       while(l && (l != &myrpt->links)){
+                               if(numoflinks >= MAX_STAT_LINKS){
+                                       ast_log(LOG_NOTICE,
+                                       "maximum number of links exceeds %d in rpt_do_stats()!",MAX_STAT_LINKS);
+                                       break;
+                               }
+                               if (l->name[0] == '0'){ /* Skip '0' nodes */
                                        reverse_patch_state = "UP";
                                        l = l->next;
                                        continue;
                                }
                                        reverse_patch_state = "UP";
                                        l = l->next;
                                        continue;
                                }
-                               listoflinks[j] = ast_strdupa(l->name);
-                               if (listoflinks[j])
-                                       j++;
+                               listoflinks[numoflinks] = ast_strdup(l->name);
+                               if(listoflinks[numoflinks] == NULL){
+                                       break;
+                               }
+                               else{
+                                       numoflinks++;
+                               }
                                l = l->next;
                        }
 
                                l = l->next;
                        }
 
-                       lastnodewhichkeyedusup = ast_strdupa(myrpt->lastnodewhichkeyedusup);                    
-                       if ((!lastnodewhichkeyedusup) || (ast_strlen_zero(lastnodewhichkeyedusup)))
-                               lastnodewhichkeyedusup = not_applicable;
-
-                       if (myrpt->keyed)
+                       if(myrpt->keyed)
                                input_signal = "YES";
                        else
                                input_signal = "NO";
 
                                input_signal = "YES";
                        else
                                input_signal = "NO";
 
-                       if (myrpt->enable)
-                               enable_state = "YES";
+                       if(myrpt->p.parrotmode)
+                               parrot_ena = "ENABLED";
                        else
                        else
-                               enable_state = "NO";
+                               parrot_ena = "DISABLED";
 
 
-                       if (!myrpt->totimer)
+                       if(myrpt->p.s[myrpt->p.sysstate_cur].txdisable)
+                               sys_ena = "DISABLED";
+                       else
+                               sys_ena = "ENABLED";
+
+                       if(myrpt->p.s[myrpt->p.sysstate_cur].totdisable)
+                               tot_ena = "DISABLED";
+                       else
+                               tot_ena = "ENABLED";
+
+                       if(myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable)
+                               link_ena = "DISABLED";
+                       else
+                               link_ena = "ENABLED";
+
+                       if(myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
+                               patch_ena = "DISABLED";
+                       else
+                               patch_ena = "ENABLED";
+
+                       if(myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable)
+                               sch_ena = "DISABLED";
+                       else
+                               sch_ena = "ENABLED";
+
+                       if(myrpt->p.s[myrpt->p.sysstate_cur].userfundisable)
+                               user_funs = "DISABLED";
+                       else
+                               user_funs = "ENABLED";
+
+                       if(myrpt->p.s[myrpt->p.sysstate_cur].alternatetail)
+                               tail_type = "ALTERNATE";
+                       else
+                               tail_type = "STANDARD";
+
+                       if(!myrpt->totimer)
                                tot_state = "TIMED OUT!";
                                tot_state = "TIMED OUT!";
-                       else if (myrpt->totimer != myrpt->p.totime)
+                       else if(myrpt->totimer != myrpt->p.totime)
                                tot_state = "ARMED";
                        else
                                tot_state = "RESET";
 
                                tot_state = "ARMED";
                        else
                                tot_state = "RESET";
 
-                       if (myrpt->tailid)
+                       if(myrpt->tailid)
                                ider_state = "QUEUED IN TAIL";
                                ider_state = "QUEUED IN TAIL";
-                       else if (myrpt->mustid)
+                       else if(myrpt->mustid)
                                ider_state = "QUEUED FOR CLEANUP";
                        else
                                ider_state = "CLEAN";
 
                                ider_state = "QUEUED FOR CLEANUP";
                        else
                                ider_state = "CLEAN";
 
-                       switch (myrpt->callmode) {
-                       case 1:
-                               patch_state = "DIALING";
-                               break;
-                       case 2:
-                               patch_state = "CONNECTING";
-                               break;
-                       case 3:
-                               patch_state = "UP";
-                               break;
-                       case 4:
-                               patch_state = "CALL FAILED";
-                               break;
-                       default:
-                               patch_state = "DOWN";
-                       }
+                       switch(myrpt->callmode){
+                               case 1:
+                                       patch_state = "DIALING";
+                                       break;
+                               case 2:
+                                       patch_state = "CONNECTING";
+                                       break;
+                               case 3:
+                                       patch_state = "UP";
+                                       break;
+
+                               case 4:
+                                       patch_state = "CALL FAILED";
+                                       break;
 
 
-                       if (!ast_strlen_zero(myrpt->exten))
-                               called_number = ast_strdupa(myrpt->exten);
+                               default:
+                                       patch_state = "DOWN";
+                       }
 
 
-                       if (!ast_strlen_zero(myrpt->lastdtmfcommand))
-                               lastdtmfcommand = ast_strdupa(myrpt->lastdtmfcommand);
+                       if(strlen(myrpt->exten)){
+                               called_number = ast_strdup(myrpt->exten);
+                       }
 
 
+                       if(strlen(myrpt->lastdtmfcommand)){
+                               lastdtmfcommand = ast_strdup(myrpt->lastdtmfcommand);
+                       }
                        rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
 
                        rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
 
-                       ast_cli(a->fd, "************************ NODE %s STATISTICS *************************\n\n", myrpt->name);
-                       ast_cli(a->fd, "Signal on input..................................: %s\n", input_signal);
-                       ast_cli(a->fd, "Transmitter enabled..............................: %s\n", enable_state);
-                       ast_cli(a->fd, "Time out timer state.............................: %s\n", tot_state);
-                       ast_cli(a->fd, "Time outs since system initialization............: %d\n", timeouts);
-                       ast_cli(a->fd, "Identifier state.................................: %s\n", ider_state);
-                       ast_cli(a->fd, "Kerchunks today..................................: %d\n", dailykerchunks);
-                       ast_cli(a->fd, "Kerchunks since system initialization............: %d\n", totalkerchunks);
-                       ast_cli(a->fd, "Keyups today.....................................: %d\n", dailykeyups);
-                       ast_cli(a->fd, "Keyups since system initialization...............: %d\n", totalkeyups);
-                       ast_cli(a->fd, "DTMF commands today..............................: %d\n", dailyexecdcommands);
-                       ast_cli(a->fd, "DTMF commands since system initialization........: %d\n", totalexecdcommands);
-                       ast_cli(a->fd, "Last DTMF command executed.......................: %s\n", lastdtmfcommand);
-
-                       hours = dailytxtime / 3600000;
+                       ast_cli(fd, "************************ NODE %s STATISTICS *************************\n\n", myrpt->name);
+                       ast_cli(fd, "Selected system state............................: %d\n", myrpt->p.sysstate_cur);
+                       ast_cli(fd, "Signal on input..................................: %s\n", input_signal);
+                       ast_cli(fd, "System...........................................: %s\n", sys_ena);
+                       ast_cli(fd, "Parrot Mode......................................: %s\n", parrot_ena);
+                       ast_cli(fd, "Scheduler........................................: %s\n", sch_ena);
+                       ast_cli(fd, "Tail Time........................................: %s\n", tail_type);
+                       ast_cli(fd, "Time out timer...................................: %s\n", tot_ena);
+                       ast_cli(fd, "Time out timer state.............................: %s\n", tot_state);
+                       ast_cli(fd, "Time outs since system initialization............: %d\n", timeouts);
+                       ast_cli(fd, "Identifier state.................................: %s\n", ider_state);
+                       ast_cli(fd, "Kerchunks today..................................: %d\n", dailykerchunks);
+                       ast_cli(fd, "Kerchunks since system initialization............: %d\n", totalkerchunks);
+                       ast_cli(fd, "Keyups today.....................................: %d\n", dailykeyups);
+                       ast_cli(fd, "Keyups since system initialization...............: %d\n", totalkeyups);
+                       ast_cli(fd, "DTMF commands today..............................: %d\n", dailyexecdcommands);
+                       ast_cli(fd, "DTMF commands since system initialization........: %d\n", totalexecdcommands);
+                       ast_cli(fd, "Last DTMF command executed.......................: %s\n", 
+                       (lastdtmfcommand && strlen(lastdtmfcommand)) ? lastdtmfcommand : not_applicable);
+                       hours = dailytxtime/3600000;
                        dailytxtime %= 3600000;
                        dailytxtime %= 3600000;
-                       minutes = dailytxtime / 60000;
+                       minutes = dailytxtime/60000;
                        dailytxtime %= 60000;
                        dailytxtime %= 60000;
-                       seconds = dailytxtime / 1000;
+                       seconds = dailytxtime/1000;
                        dailytxtime %= 1000;
 
                        dailytxtime %= 1000;
 
-                       ast_cli(a->fd, "TX time today ...................................: %02d:%02d:%02d.%d\n",
+                       ast_cli(fd, "TX time today....................................: %02d:%02d:%02d.%d\n",
                                hours, minutes, seconds, dailytxtime);
 
                                hours, minutes, seconds, dailytxtime);
 
-                       hours = (int) totaltxtime / 3600000;
+                       hours = (int) totaltxtime/3600000;
                        totaltxtime %= 3600000;
                        totaltxtime %= 3600000;
-                       minutes = (int) totaltxtime / 60000;
+                       minutes = (int) totaltxtime/60000;
                        totaltxtime %= 60000;
                        totaltxtime %= 60000;
-                       seconds = (int)  totaltxtime / 1000;
+                       seconds = (int)  totaltxtime/1000;
                        totaltxtime %= 1000;
 
                        totaltxtime %= 1000;
 
-                       ast_cli(a->fd, "TX time since system initialization..............: %02d:%02d:%02d.%d\n",
+                       ast_cli(fd, "TX time since system initialization..............: %02d:%02d:%02d.%d\n",
                                 hours, minutes, seconds, (int) totaltxtime);
                                 hours, minutes, seconds, (int) totaltxtime);
-                       ast_cli(a->fd, "Nodes currently connected to us..................: ");
-                       for (j = 0;; j++) {
-                               if (!listoflinks[j]) {
-                                       if (!j) {
-                                               ast_cli(a->fd, "<NONE>");
+
+                               hours = uptime/3600;
+                        uptime %= 3600;
+                        minutes = uptime/60;
+                        uptime %= 60;
+
+                        ast_cli(fd, "Uptime...........................................: %02d:%02d:%02d\n",
+                                hours, minutes, uptime);
+
+                       ast_cli(fd, "Nodes currently connected to us..................: ");
+                        if(!numoflinks){
+                             ast_cli(fd,"<NONE>");
+                        }
+                       else{
+                               for(j = 0 ;j < numoflinks; j++){
+                                       ast_cli(fd, "%s", listoflinks[j]);
+                                       if(j % 4 == 3){
+                                               ast_cli(fd, "\n");
+                                               ast_cli(fd, "                                                 : ");
+                                       }       
+                                       else{
+                                               if((numoflinks - 1) - j  > 0)
+                                                       ast_cli(fd, ", ");
                                        }
                                        }
-                                       break;
-                               }
-                               ast_cli(a->fd, "%s", listoflinks[j]);
-                               if (j % 4 == 3) {
-                                       ast_cli(a->fd, "\n");
-                                       ast_cli(a->fd, "                                                 : ");
-                               } else {
-                                       if (listoflinks[j + 1])
-                                               ast_cli(a->fd, ", ");
                                }
                        }
                                }
                        }
-                       ast_cli(a->fd, "\n");
-
-                       ast_cli(a->fd, "Last node which transmitted to us................: %s\n", lastnodewhichkeyedusup);
-                       ast_cli(a->fd, "Autopatch state..................................: %s\n", patch_state);
-                       ast_cli(a->fd, "Autopatch called number..........................: %s\n", called_number);
-                       ast_cli(a->fd, "Reverse patch/IAXRPT connected...................: %s\n\n", reverse_patch_state);
-
-                       return CLI_SUCCESS;
+                       ast_cli(fd,"\n");
+
+                       ast_cli(fd, "Autopatch........................................: %s\n", patch_ena);
+                       ast_cli(fd, "Autopatch state..................................: %s\n", patch_state);
+                       ast_cli(fd, "Autopatch called number..........................: %s\n",
+                       (called_number && strlen(called_number)) ? called_number : not_applicable);
+                       ast_cli(fd, "Reverse patch/IAXRPT connected...................: %s\n", reverse_patch_state);
+                       ast_cli(fd, "User linking commands............................: %s\n", link_ena);
+                       ast_cli(fd, "User functions...................................: %s\n\n", user_funs);
+
+                       for(j = 0; j < numoflinks; j++){ /* ast_free() all link names */
+                               ast_free(listoflinks[j]);
+                       }
+                       if(called_number){
+                               ast_free(called_number);
+                       }
+                       if(lastdtmfcommand){
+                               ast_free(lastdtmfcommand);
+                       }
+                       return RESULT_SUCCESS;
                }
        }
                }
        }
-       return CLI_FAILURE;
+       return RESULT_FAILURE;
 }
 
 /*
 * Link stats function
 */
 }
 
 /*
 * Link stats function
 */
-static char *handle_cli_rpt_lstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+
+static int rpt_do_lstats(int fd, int argc, char *argv[])
 {
 {
-       int i, j;
+       int i,j;
+       char *connstate;
        struct rpt *myrpt;
        struct rpt_link *l;
        struct rpt *myrpt;
        struct rpt_link *l;
-       struct rpt_lstat *s, *t;
+       struct rpt_lstat *s,*t;
        struct rpt_lstat s_head;
        struct rpt_lstat s_head;
-
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "rpt lstats";
-               e->usage =
-                       "Usage: rpt lstats <nodename>\n"
-                       "       Dumps link statistics to console\n";
-               return NULL;
-       case CLI_GENERATE:
-               return NULL;
-       }
-
-       if (a->argc != 3)
-               return CLI_SHOWUSAGE;
+       if(argc != 3)
+               return RESULT_SHOWUSAGE;
 
        s = NULL;
        s_head.next = &s_head;
        s_head.prev = &s_head;
 
 
        s = NULL;
        s_head.next = &s_head;
        s_head.prev = &s_head;
 
-       for (i = 0; i < nrpts; i++) {
-               if (!strcmp(a->argv[2], rpt_vars[i].name)) {
+       for(i = 0; i < nrpts; i++)
+       {
+               if (!strcmp(argv[2],rpt_vars[i].name)){
                        /* Make a copy of all stat variables while locked */
                        myrpt = &rpt_vars[i];
                        rpt_mutex_lock(&myrpt->lock); /* LOCK */
                        /* Traverse the list of connected nodes */
                        j = 0;
                        l = myrpt->links.next;
                        /* Make a copy of all stat variables while locked */
                        myrpt = &rpt_vars[i];
                        rpt_mutex_lock(&myrpt->lock); /* LOCK */
                        /* Traverse the list of connected nodes */
                        j = 0;
                        l = myrpt->links.next;
-                       while (l != &myrpt->links) {
-                               if (l->name[0] == '0') { /* Skip '0' nodes */
+                       while(l && (l != &myrpt->links)){
+                               if (l->name[0] == '0'){ /* Skip '0' nodes */
                                        l = l->next;
                                        continue;
                                }
                                        l = l->next;
                                        continue;
                                }
-                               if ((s = ast_calloc(1, sizeof(*s))) == NULL) {
+                               if((s = (struct rpt_lstat *) ast_malloc(sizeof(struct rpt_lstat))) == NULL){
                                        ast_log(LOG_ERROR, "Malloc failed in rpt_do_lstats\n");
                                        rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
                                        ast_log(LOG_ERROR, "Malloc failed in rpt_do_lstats\n");
                                        rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
-                                       return CLI_FAILURE;
+                                       return RESULT_FAILURE;
                                }
                                }
-                               ast_copy_string(s->name, l->name, MAXREMSTR);
-                               pbx_substitute_variables_helper(l->chan, "${IAXPEER(CURRENTCHANNEL)}", s->peer, MAXPEERSTR - 1);
+                               memset(s, 0, sizeof(struct rpt_lstat));
+                               strncpy(s->name, l->name, MAXREMSTR - 1);
+                               if (l->chan) pbx_substitute_variables_helper(l->chan, "${IAXPEER(CURRENTCHANNEL)}", s->peer, MAXPEERSTR - 1);
+                               else strcpy(s->peer,"(none)");
                                s->mode = l->mode;
                                s->outbound = l->outbound;
                                s->reconnects = l->reconnects;
                                s->connecttime = l->connecttime;
                                s->mode = l->mode;
                                s->outbound = l->outbound;
                                s->reconnects = l->reconnects;
                                s->connecttime = l->connecttime;
+                               s->thisconnected = l->thisconnected;
+                               memcpy(s->chan_stat,l->chan_stat,NRPTSTAT * sizeof(struct rpt_chan_stat));
                                insque((struct qelem *) s, (struct qelem *) s_head.next);
                                insque((struct qelem *) s, (struct qelem *) s_head.next);
+                               memset(l->chan_stat,0,NRPTSTAT * sizeof(struct rpt_chan_stat));
                                l = l->next;
                        }
                        rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
                                l = l->next;
                        }
                        rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
-                       ast_cli(a->fd, "NODE      PEER                RECONNECTS  DIRECTION  CONNECT TIME\n");
-                       ast_cli(a->fd, "----      ----                ----------  ---------  ------------\n");
+                       ast_cli(fd, "NODE      PEER                RECONNECTS  DIRECTION  CONNECT TIME        CONNECT STATE\n");
+                       ast_cli(fd, "----      ----                ----------  ---------  ------------        -------------\n");
 
 
-                       for (s = s_head.next; s != &s_head; s = s->next) {
+                       for(s = s_head.next; s != &s_head; s = s->next){
                                int hours, minutes, seconds;
                                long long connecttime = s->connecttime;
                                int hours, minutes, seconds;
                                long long connecttime = s->connecttime;
-                               char conntime[31];
+                               char conntime[21];
                                hours = (int) connecttime/3600000;
                                connecttime %= 3600000;
                                minutes = (int) connecttime/60000;
                                connecttime %= 60000;
                                seconds = (int)  connecttime/1000;
                                connecttime %= 1000;
                                hours = (int) connecttime/3600000;
                                connecttime %= 3600000;
                                minutes = (int) connecttime/60000;
                                connecttime %= 60000;
                                seconds = (int)  connecttime/1000;
                                connecttime %= 1000;
-                               snprintf(conntime, sizeof(conntime), "%02d:%02d:%02d.%d",
+                               snprintf(conntime, 20, "%02d:%02d:%02d.%d",
                                        hours, minutes, seconds, (int) connecttime);
                                        hours, minutes, seconds, (int) connecttime);
-                               ast_cli(a->fd, "%-10s%-20s%-12d%-11s%-30s\n",
-                                       s->name, s->peer, s->reconnects, (s->outbound)? "OUT":"IN", conntime);
+                               conntime[20] = 0;
+                               if(s->thisconnected)
+                                       connstate  = "ESTABLISHED";
+                               else
+                                       connstate = "CONNECTING";
+                               ast_cli(fd, "%-10s%-20s%-12d%-11s%-20s%-20s\n",
+                                       s->name, s->peer, s->reconnects, (s->outbound)? "OUT":"IN", conntime, connstate);
                        }       
                        /* destroy our local link queue */
                        s = s_head.next;
                        }       
                        /* destroy our local link queue */
                        s = s_head.next;
-                       while (s != &s_head) {
+                       while(s != &s_head){
                                t = s;
                                s = s->next;
                                remque((struct qelem *)t);
                                ast_free(t);
                        }                       
                                t = s;
                                s = s->next;
                                remque((struct qelem *)t);
                                ast_free(t);
                        }                       
-                       return CLI_SUCCESS;
+                       return RESULT_SUCCESS;
+               }
+       }
+       return RESULT_FAILURE;
+}
+
+/*
+* List all nodes connected, directly or indirectly
+*/
+
+static int rpt_do_nodes(int fd, int argc, char *argv[])
+{
+       int i,j;
+       char ns;
+       char lbuf[MAXLINKLIST],*strs[MAXLINKLIST];
+       struct rpt *myrpt;
+       if(argc != 3)
+               return RESULT_SHOWUSAGE;
+
+       for(i = 0; i < nrpts; i++)
+       {
+               if (!strcmp(argv[2],rpt_vars[i].name)){
+                       /* Make a copy of all stat variables while locked */
+                       myrpt = &rpt_vars[i];
+                       rpt_mutex_lock(&myrpt->lock); /* LOCK */
+                       __mklinklist(myrpt,NULL,lbuf);
+                       rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
+                       /* parse em */
+                       ns = finddelim(lbuf,strs,MAXLINKLIST);
+                       /* sort em */
+                       if (ns) qsort((void *)strs,ns,sizeof(char *),mycompar);
+                       ast_cli(fd,"\n");
+                       ast_cli(fd, "************************* CONNECTED NODES *************************\n\n");
+                       for(j = 0 ;; j++){
+                               if(!strs[j]){
+                                       if(!j){
+                                               ast_cli(fd,"<NONE>");
+                                       }
+                                       break;
+                               }
+                               ast_cli(fd, "%s", strs[j]);
+                               if(j % 8 == 7){
+                                       ast_cli(fd, "\n");
+                               }
+                               else{
+                                       if(strs[j + 1])
+                                               ast_cli(fd, ", ");
+                               }
+                       }
+                       ast_cli(fd,"\n\n");
+                       return RESULT_SUCCESS;
                }
        }
                }
        }
+       return RESULT_FAILURE;
+}
+
+/*
+* List all locally configured nodes
+*/
+
+static int rpt_do_local_nodes(int fd, int argc, char *argv[])
+{
+
+    int i;
+    ast_cli(fd, "\nNode\n----\n");
+    for (i=0; i< nrpts; i++)
+    {
+        ast_cli(fd, "%s\n", rpt_vars[i].name);        
+    } /* for i */
+    ast_cli(fd,"\n");
+    return RESULT_SUCCESS;
+} 
+
+
+/*
+* reload vars 
+*/
+
+static int rpt_do_reload(int fd, int argc, char *argv[])
+{
+int    n;
+
+        if (argc > 2) return RESULT_SHOWUSAGE;
 
 
-       return CLI_FAILURE;
+       for(n = 0; n < nrpts; n++) rpt_vars[n].reload = 1;
+
+       return RESULT_FAILURE;
 }
 
 /*
 }
 
 /*
-* reload vars 
+* restart app_rpt
 */
 */
-static char *handle_cli_rpt_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+                                                                                                                                 
+static int rpt_do_restart(int fd, int argc, char *argv[])
 {
 {
-       int     n;
+int    i;
 
 
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "rpt reload";
-               e->usage =
-                       "Usage: rpt reload\n"
-                       "       Reloads app_rpt running config parameters\n";
-               return NULL;
-       case CLI_GENERATE:
-               return NULL;
+        if (argc > 2) return RESULT_SHOWUSAGE;
+       for(i = 0; i < nrpts; i++)
+       {
+               if (rpt_vars[i].rxchannel) ast_softhangup(rpt_vars[i].rxchannel,AST_SOFTHANGUP_DEV);
        }
        }
+       return RESULT_FAILURE;
+}
+
 
 
-       if (a->argc > 2)
-               return CLI_SHOWUSAGE;
+/*
+* send an app_rpt DTMF function from the CLI
+*/
+                                                                                                                                 
+static int rpt_do_fun(int fd, int argc, char *argv[])
+{
+       int     i,busy=0;
 
 
-       for (n = 0; n < nrpts; n++)
-               rpt_vars[n].reload = 1;
+        if (argc != 4) return RESULT_SHOWUSAGE;
 
 
-       return CLI_SUCCESS;
+       for(i = 0; i < nrpts; i++){
+               if(!strcmp(argv[2], rpt_vars[i].name)){
+                       struct rpt *myrpt = &rpt_vars[i];
+                       rpt_mutex_lock(&myrpt->lock);
+                       if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(argv[3])){
+                               rpt_mutex_unlock(&myrpt->lock);
+                               busy=1;
+                       }
+                       if(!busy){
+                               myrpt->macrotimer = MACROTIME;
+                               strncat(myrpt->macrobuf,argv[3],MAXMACRO - 1);
+                       }
+                       rpt_mutex_unlock(&myrpt->lock);
+               }
+       }
+       if(busy){
+               ast_cli(fd, "Function decoder busy");
+       }
+       return RESULT_FAILURE;
 }
 }
+/*
+       the convention is that macros in the data from the rpt() application
+       are all at the end of the data, separated by the | and start with a *
+       when put into the macro buffer, the characters have their high bit
+       set so the macro processor knows they came from the application data
+       and to use the alt-functions table.
+       sph:
+*/
+static int rpt_push_alt_macro(struct rpt *myrpt, char *sptr)
+{
+       int     busy=0;
+
+       rpt_mutex_lock(&myrpt->lock);
+       if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(sptr)){
+               rpt_mutex_unlock(&myrpt->lock);
+               busy=1;
+       }
+       if(!busy){
+               int x;
+               if (debug)ast_log(LOG_NOTICE, "rpt_push_alt_macro %s\n",sptr);
+               myrpt->macrotimer = MACROTIME;
+               for(x = 0; *(sptr + x); x++)
+                   myrpt->macrobuf[x] = *(sptr + x) | 0x80;
+               *(sptr + x) = 0;
+       }
+       rpt_mutex_unlock(&myrpt->lock);
+
+       if(busy)ast_log(LOG_WARNING, "Function decoder busy on app_rpt command macro.\n");
 
 
+       return busy;
+}
 /*
 /*
-* restart app_rpt
+       allows us to test rpt() application data commands
 */
 */
-static char *handle_cli_rpt_restart(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static int rpt_do_fun1(int fd, int argc, char *argv[])
 {
        int     i;
 
 {
        int     i;
 
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "rpt restart";
-               e->usage =
-                       "Usage: rpt restart\n"
-                       "       Restarts app_rpt\n";
-               return NULL;
-       case CLI_GENERATE:
-               return NULL;
-       }
+    if (argc != 4) return RESULT_SHOWUSAGE;
 
 
-       if (a->argc > 2)
-               return CLI_SHOWUSAGE;
-       for (i = 0; i < nrpts; i++) {
-               if (rpt_vars[i].rxchannel)
-                       ast_softhangup(rpt_vars[i].rxchannel, AST_SOFTHANGUP_DEV);
+       for(i = 0; i < nrpts; i++){
+               if(!strcmp(argv[2], rpt_vars[i].name)){
+                       struct rpt *myrpt = &rpt_vars[i];
+                       rpt_push_alt_macro(myrpt,argv[3]);
+               }
        }
        }
-       return CLI_SUCCESS;
+       return RESULT_FAILURE;
 }
 }
+/*
+* send an app_rpt **command** from the CLI
+*/
+
+static int rpt_do_cmd(int fd, int argc, char *argv[])
+{
+       int i, l;
+       int busy=0;
+       int maxActions = sizeof(function_table)/sizeof(struct function_table_tag);
+
+       int thisRpt = -1;
+       int thisAction = -1;
+       struct rpt *myrpt = NULL;
+       if (argc != 6) return RESULT_SHOWUSAGE;
+       
+       for(i = 0; i < nrpts; i++)
+       {
+               if(!strcmp(argv[2], rpt_vars[i].name))
+               {
+                       thisRpt = i;
+                       myrpt = &rpt_vars[i];
+                       break;
+               } /* if !strcmp... */
+       } /* for i */
+
+       if (thisRpt < 0)
+       {
+               ast_cli(fd, "Unknown node number %s.\n", argv[2]);
+               return RESULT_FAILURE;
+       } /* if thisRpt < 0 */
+       
+       /* Look up the action */
+       l = strlen(argv[3]);
+       for(i = 0 ; i < maxActions; i++)
+       {
+               if(!strncasecmp(argv[3], function_table[i].action, l))
+               {
+                       thisAction = i;
+                       break;
+               } /* if !strncasecmp... */
+       } /* for i */
+       
+       if (thisAction < 0)
+       {
+               ast_cli(fd, "Unknown action name %s.\n", argv[3]);
+               return RESULT_FAILURE;
+       } /* if thisAction < 0 */
+
+       /* at this point, it looks like all the arguments make sense... */
+
+       rpt_mutex_lock(&myrpt->lock);
+
+       if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE)
+       {
+               rpt_vars[thisRpt].cmdAction.state = CMD_STATE_BUSY;
+               rpt_vars[thisRpt].cmdAction.functionNumber = thisAction;
+               strncpy(rpt_vars[thisRpt].cmdAction.param, argv[4], MAXDTMF);
+               strncpy(rpt_vars[thisRpt].cmdAction.digits, argv[5], MAXDTMF);
+               rpt_vars[thisRpt].cmdAction.command_source = SOURCE_RPT;
+               rpt_vars[thisRpt].cmdAction.state = CMD_STATE_READY;
+       } /* if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE */
+       else
+       {
+               busy = 1;
+       } /* if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE */
+       rpt_mutex_unlock(&myrpt->lock);
+
+       return (busy ? RESULT_FAILURE : RESULT_SUCCESS);
+} /* rpt_do_cmd() */
 
 static int play_tone_pair(struct ast_channel *chan, int f1, int f2, int duration, int amplitude)
 {
        int res;
 
 
 static int play_tone_pair(struct ast_channel *chan, int f1, int f2, int duration, int amplitude)
 {
        int res;
 
-       if ((res = ast_tonepair_start(chan, f1, f2, duration, amplitude)))
-               return res;
-
-       while (chan->generatordata) {
-               if (ast_safe_sleep(chan, 1))
-                       return -1;
+        if ((res = ast_tonepair_start(chan, f1, f2, duration, amplitude)))
+                return res;
+                                                                                                                                            
+        while(chan->generatordata) {
+               if (ast_safe_sleep(chan,1)) return -1;
        }
 
        }
 
-       return 0;
+        return 0;
 }
 
 static int play_tone(struct ast_channel *chan, int freq, int duration, int amplitude)
 }
 
 static int play_tone(struct ast_channel *chan, int freq, int duration, int amplitude)
@@ -1492,11 +3270,197 @@ static int play_silence(struct ast_channel *chan, int duration)
        return play_tone_pair(chan, 0, 0, duration, 0);
 }
 
        return play_tone_pair(chan, 0, 0, duration, 0);
 }
 
+#ifdef NEW_ASTERISK
+
+static char *res2cli(int r)
+
+{
+       switch (r)
+       {
+           case RESULT_SUCCESS:
+               return(CLI_SUCCESS);
+           case RESULT_SHOWUSAGE:
+               return(CLI_SHOWUSAGE);
+           default:
+               return(CLI_FAILURE);
+       }
+}
+
+static char *handle_cli_debug(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt debug level";
+                e->usage = debug_usage;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_debug(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_dump(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt dump level";
+                e->usage = dump_usage;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_dump(a->fd,a->argc,a->argv));
+}
+
+
+static char *handle_cli_stats(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt stats";
+                e->usage = dump_stats;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_stats(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_nodes(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt nodes";
+                e->usage = dump_nodes;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_nodes(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_local_nodes(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt localnodes";
+                e->usage = usage_local_nodes;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_local_nodes(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_lstats(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt lstats";
+                e->usage = dump_lstats;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_lstats(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_reload(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt reload";
+                e->usage = reload_usage;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_reload(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_restart(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt restart";
+                e->usage = restart_usage;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_restart(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_fun(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt fun";
+                e->usage = fun_usage;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_fun(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_fun1(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt fun1";
+                e->usage = fun_usage;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_fun1(a->fd,a->argc,a->argv));
+}
+
+static char *handle_cli_cmd(struct ast_cli_entry *e,
+       int cmd, struct ast_cli_args *a)
+{
+        switch (cmd) {
+        case CLI_INIT:
+                e->command = "rpt cmd";
+                e->usage = cmd_usage;
+                return NULL;
+        case CLI_GENERATE:
+                return NULL;
+       }
+       return res2cli(rpt_do_cmd(a->fd,a->argc,a->argv));
+}
+
+static struct ast_cli_entry rpt_cli[] = {
+       AST_CLI_DEFINE(handle_cli_debug,"Enable app_rpt debugging"),
+       AST_CLI_DEFINE(handle_cli_dump,"Dump app_rpt structs for debugging"),
+       AST_CLI_DEFINE(handle_cli_stats,"Dump node statistics"),
+       AST_CLI_DEFINE(handle_cli_nodes,"Dump node list"),
+       AST_CLI_DEFINE(handle_cli_local_nodes,  "Dump list of local node numbers"),
+       AST_CLI_DEFINE(handle_cli_lstats,"Dump link statistics"),
+       AST_CLI_DEFINE(handle_cli_reload,"Reload app_rpt config"),
+       AST_CLI_DEFINE(handle_cli_restart,"Restart app_rpt"),
+       AST_CLI_DEFINE(handle_cli_fun,"Execute a DTMF function"),
+       AST_CLI_DEFINE(handle_cli_fun1,"Execute a DTMF function"),
+       AST_CLI_DEFINE(handle_cli_cmd,"Execute a DTMF function")
+};
+
+#endif
 
 
-static int send_morse(struct ast_channel *chan, const char *string, int speed, int freq, int amplitude)
+static int send_morse(struct ast_channel *chan, char *string, int speed, int freq, int amplitude)
 {
 
 {
 
-       static struct morse_bits mbits[] = {
+static struct morse_bits mbits[] = {
                {0, 0}, /* SPACE */
                {0, 0}, 
                {6, 18},/* " */
                {0, 0}, /* SPACE */
                {0, 0}, 
                {6, 18},/* " */
@@ -1530,8 +3494,8 @@ static int send_morse(struct ast_channel *chan, const char *string, int speed, i
                {0, 0},
                {6, 12},/* ? */
                {0, 0},
                {0, 0},
                {6, 12},/* ? */
                {0, 0},
-               {2, 2}, /* A */
-               {4, 1}, /* B */
+               {2, 2}, /* A */
+               {4, 1}, /* B */
                {4, 5}, /* C */
                {3, 1}, /* D */
                {1, 0}, /* E */
                {4, 5}, /* C */
                {3, 1}, /* D */
                {1, 0}, /* E */
@@ -1558,6 +3522,7 @@ static int send_morse(struct ast_channel *chan, const char *string, int speed, i
                {4, 3}  /* Z */
        };
 
                {4, 3}  /* Z */
        };
 
+
        int dottime;
        int dashtime;
        int intralettertime;
        int dottime;
        int dashtime;
        int intralettertime;
@@ -1573,33 +3538,33 @@ static int send_morse(struct ast_channel *chan, const char *string, int speed, i
        
        /* Approximate the dot time from the speed arg. */
        
        
        /* Approximate the dot time from the speed arg. */
        
-       dottime = 900 / speed;
+       dottime = 900/speed;
        
        
-       /* Establish timing relationships */
+       /* Establish timing releationships */
        
        dashtime = 3 * dottime;
        intralettertime = dottime;
        interlettertime = dottime * 4 ;
        interwordtime = dottime * 7;
        
        
        dashtime = 3 * dottime;
        intralettertime = dottime;
        interlettertime = dottime * 4 ;
        interwordtime = dottime * 7;
        
-       for (; (*string) && (!res); string++) {
+       for(;(*string) && (!res); string++){
        
                c = *string;
                
                /* Convert lower case to upper case */
                
        
                c = *string;
                
                /* Convert lower case to upper case */
                
-               if ((c >= 'a') && (c <= 'z'))
+               if((c >= 'a') && (c <= 'z'))
                        c -= 0x20;
                
                /* Can't deal with any char code greater than Z, skip it */
                
                        c -= 0x20;
                
                /* Can't deal with any char code greater than Z, skip it */
                
-               if (c  > 'Z')
+               if(c  > 'Z')
                        continue;
                
                /* If space char, wait the inter word time */
                                        
                        continue;
                
                /* If space char, wait the inter word time */
                                        
-               if (c == ' ') {
-                       if (!res)
+               if(c == ' '){
+                       if(!res)
                                res = play_silence(chan, interwordtime);
                        continue;
                }
                                res = play_silence(chan, interwordtime);
                        continue;
                }
@@ -1615,17 +3580,17 @@ static int send_morse(struct ast_channel *chan, const char *string, int speed, i
                
                /* Send the character */
                
                
                /* Send the character */
                
-               for (; len ; len--) {
-                       if (!res)
+               for(; len ; len--){
+                       if(!res)
                                res = play_tone(chan, freq, (ddcomb & 1) ? dashtime : dottime, amplitude);
                                res = play_tone(chan, freq, (ddcomb & 1) ? dashtime : dottime, amplitude);
-                       if (!res)
+                       if(!res)
                                res = play_silence(chan, intralettertime);
                        ddcomb >>= 1;
                }
                
                /* Wait the interletter time */
                
                                res = play_silence(chan, intralettertime);
                        ddcomb >>= 1;
                }
                
                /* Wait the interletter time */
                
-               if (!res)
+               if(!res)
                        res = play_silence(chan, interlettertime - intralettertime);
        }
        
                        res = play_silence(chan, interlettertime - intralettertime);
        }
        
@@ -1639,12 +3604,12 @@ static int send_morse(struct ast_channel *chan, const char *string, int speed, i
        * Wait for the zaptel driver to physically write the tone blocks to the hardware
        */
 
        * Wait for the zaptel driver to physically write the tone blocks to the hardware
        */
 
-       for (i = 0; i < 20 ; i++) {
+       for(i = 0; i < 20 ; i++){
                flags =  ZT_IOMUX_WRITEEMPTY | ZT_IOMUX_NOWAIT; 
                res = ioctl(chan->fds[0], ZT_IOMUX, &flags);
                flags =  ZT_IOMUX_WRITEEMPTY | ZT_IOMUX_NOWAIT; 
                res = ioctl(chan->fds[0], ZT_IOMUX, &flags);
-               if (flags & ZT_IOMUX_WRITEEMPTY)
+               if(flags & ZT_IOMUX_WRITEEMPTY)
                        break;
                        break;
-               if ( ast_safe_sleep(chan, 50)) {
+               if( ast_safe_sleep(chan, 50)){
                        res = -1;
                        break;
                }
                        res = -1;
                        break;
                }
@@ -1654,11 +3619,11 @@ static int send_morse(struct ast_channel *chan, const char *string, int speed, i
        return res;
 }
 
        return res;
 }
 
-static int send_tone_telemetry(struct ast_channel *chan, const char *tonestring)
+static int send_tone_telemetry(struct ast_channel *chan, char *tonestring)
 {
 {
-       char *stringp;
+       char *p,*stringp;
        char *tonesubset;
        char *tonesubset;
-       int f1, f2;
+       int f1,f2;
        int duration;
        int amplitude;
        int res;
        int duration;
        int amplitude;
        int res;
@@ -1666,48 +3631,54 @@ static int send_tone_telemetry(struct ast_channel *chan, const char *tonestring)
        int flags;
        
        res = 0;
        int flags;
        
        res = 0;
+
+       if(!tonestring)
+               return res;
        
        
-       stringp = ast_strdupa(tonestring);
+       p = stringp = ast_strdup(tonestring);
 
 
-       for (;tonestring;) {
-               tonesubset = strsep(&stringp, ")");
-               if (!tonesubset)
+       for(;tonestring;){
+               tonesubset = strsep(&stringp,")");
+               if(!tonesubset)
                        break;
                        break;
-               if (sscanf(tonesubset, "(%d,%d,%d,%d", &f1, &f2, &duration, &amplitude) != 4)
+               if(sscanf(tonesubset,"(%d,%d,%d,%d", &f1, &f2, &duration, &amplitude) != 4)
                        break;
                res = play_tone_pair(chan, f1, f2, duration, amplitude);
                        break;
                res = play_tone_pair(chan, f1, f2, duration, amplitude);
-               if (res)
+               if(res)
                        break;
        }
                        break;
        }
-       if (!res)
+       if(p)
+               ast_free(p);
+       if(!res)
                res = play_tone_pair(chan, 0, 0, 100, 0); /* This is needed to ensure the last tone segment is timed correctly */
        
        if (!res) 
                res = ast_waitstream(chan, "");
                res = play_tone_pair(chan, 0, 0, 100, 0); /* This is needed to ensure the last tone segment is timed correctly */
        
        if (!res) 
                res = ast_waitstream(chan, "");
+
        ast_stopstream(chan);
 
        /*
        * Wait for the zaptel driver to physically write the tone blocks to the hardware
        */
 
        ast_stopstream(chan);
 
        /*
        * Wait for the zaptel driver to physically write the tone blocks to the hardware
        */
 
-       for (i = 0; i < 20 ; i++) {
+       for(i = 0; i < 20 ; i++){
                flags =  ZT_IOMUX_WRITEEMPTY | ZT_IOMUX_NOWAIT; 
                res = ioctl(chan->fds[0], ZT_IOMUX, &flags);
                flags =  ZT_IOMUX_WRITEEMPTY | ZT_IOMUX_NOWAIT; 
                res = ioctl(chan->fds[0], ZT_IOMUX, &flags);
-               if (flags & ZT_IOMUX_WRITEEMPTY)
+               if(flags & ZT_IOMUX_WRITEEMPTY)
                        break;
                        break;
-               if (ast_safe_sleep(chan, 50)) {
+               if( ast_safe_sleep(chan, 50)){
                        res = -1;
                        break;
                }
        }
                
        return res;
                        res = -1;
                        break;
                }
        }
                
        return res;
+               
 }
 }
-       
 
 
-static int sayfile(struct ast_channel *mychannel, const char *fname)
+static int sayfile(struct ast_channel *mychannel,char *fname)
 {
 {
-       int     res;
+int    res;
 
        res = ast_streamfile(mychannel, fname, mychannel->language);
        if (!res) 
 
        res = ast_streamfile(mychannel, fname, mychannel->language);
        if (!res) 
@@ -1718,11 +3689,11 @@ static int sayfile(struct ast_channel *mychannel, const char *fname)
        return res;
 }
 
        return res;
 }
 
-static int saycharstr(struct ast_channel *mychannel, char *str)
+static int saycharstr(struct ast_channel *mychannel,char *str)
 {
 {
-       int     res;
+int    res;
 
 
-       res = ast_say_character_str(mychannel, str, NULL, mychannel->language);
+       res = ast_say_character_str(mychannel,str,NULL,mychannel->language);
        if (!res) 
                res = ast_waitstream(mychannel, "");
        else
        if (!res) 
                res = ast_waitstream(mychannel, "");
        else
@@ -1735,7 +3706,7 @@ static int saynum(struct ast_channel *mychannel, int num)
 {
        int res;
        res = ast_say_number(mychannel, num, NULL, mychannel->language, NULL);
 {
        int res;
        res = ast_say_number(mychannel, num, NULL, mychannel->language, NULL);
-       if (!res)
+       if(!res)
                res = ast_waitstream(mychannel, "");
        else
                ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                res = ast_waitstream(mychannel, "");
        else
                ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
@@ -1743,20 +3714,26 @@ static int saynum(struct ast_channel *mychannel, int num)
        return res;
 }
 
        return res;
 }
 
-static int saydigits(struct ast_channel *mychannel, int num)
+/* say a node and nodename. Try to look in dir referred to by nodenames in
+config, and see if there's a custom node file to play, and if so, play it */
+
+static int saynode(struct rpt *myrpt, struct ast_channel *mychannel, char *name)
 {
 {
-       int res;
-       res = ast_say_digits(mychannel, num, NULL, mychannel->language);
-       if (!res)
-               res = ast_waitstream(mychannel, "");
-       else
-               ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
-       ast_stopstream(mychannel);
+int    res;
+char   *val,fname[300];
+
+       val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "nodenames");
+       if (!val) val = NODENAMES;
+       snprintf(fname,sizeof(fname) - 1,"%s/%s",val,name);
+       if (ast_fileexists(fname,NULL,mychannel->language) > 0)
+               return(sayfile(mychannel,fname));
+       res = sayfile(mychannel,"rpt/node");
+       if (!res) 
+               res = ast_say_character_str(mychannel,name,NULL,mychannel->language);
        return res;
 }
 
        return res;
 }
 
-
-static int telem_any(struct rpt *myrpt, struct ast_channel *chan, const char *entry)
+static int telem_any(struct rpt *myrpt,struct ast_channel *chan, char *entry)
 {
        int res;
        char c;
 {
        int res;
        char c;
@@ -1770,35 +3747,38 @@ static int telem_any(struct rpt *myrpt, struct ast_channel *chan, const char *en
        
        res = 0;
        
        
        res = 0;
        
-       if (!morseidfreq) { /* Get the morse parameters if not already loaded */
+       if(!morseidfreq){ /* Get the morse parameters if not already loaded */
                morsespeed = retrieve_astcfgint(myrpt, mcat, "speed", 5, 20, 20);
                morsespeed = retrieve_astcfgint(myrpt, mcat, "speed", 5, 20, 20);
-               morsefreq = retrieve_astcfgint(myrpt, mcat, "frequency", 300, 3000, 800);
-               morseampl = retrieve_astcfgint(myrpt, mcat, "amplitude", 200, 8192, 4096);
+               morsefreq = retrieve_astcfgint(myrpt, mcat, "frequency", 300, 3000, 800);
+               morseampl = retrieve_astcfgint(myrpt, mcat, "amplitude", 200, 8192, 4096);
                morseidampl = retrieve_astcfgint(myrpt, mcat, "idamplitude", 200, 8192, 2048);
                morseidfreq = retrieve_astcfgint(myrpt, mcat, "idfrequency", 300, 3000, 330);   
        }
        
        /* Is it a file, or a tone sequence? */
                        
                morseidampl = retrieve_astcfgint(myrpt, mcat, "idamplitude", 200, 8192, 2048);
                morseidfreq = retrieve_astcfgint(myrpt, mcat, "idfrequency", 300, 3000, 330);   
        }
        
        /* Is it a file, or a tone sequence? */
                        
-       if (entry[0] == '|') {
+       if(entry[0] == '|'){
                c = entry[1];
                c = entry[1];
-               if ((c >= 'a') && (c <= 'z'))
+               if((c >= 'a')&&(c <= 'z'))
                        c -= 0x20;
        
                        c -= 0x20;
        
-               switch (c) {
-               case 'I': /* Morse ID */
-                       res = send_morse(chan, entry + 2, morsespeed, morseidfreq, morseidampl);
-                       break;
-               case 'M': /* Morse Message */
-                       res = send_morse(chan, entry + 2, morsespeed, morsefreq, morseampl);
-                       break;
-               case 'T': /* Tone sequence */
-                       res = send_tone_telemetry(chan, entry + 2);
-                       break;
-               default:
-                       res = -1;
+               switch(c){
+                       case 'I': /* Morse ID */
+                               res = send_morse(chan, entry + 2, morsespeed, morseidfreq, morseidampl);
+                               break;
+                       
+                       case 'M': /* Morse Message */
+                               res = send_morse(chan, entry + 2, morsespeed, morsefreq, morseampl);
+                               break;
+                       
+                       case 'T': /* Tone sequence */
+                               res = send_tone_telemetry(chan, entry + 2);
+                               break;
+                       default:
+                               res = -1;
                }
                }
-       } else
+       }
+       else
                res = sayfile(chan, entry); /* File */
        return res;
 }
                res = sayfile(chan, entry); /* File */
        return res;
 }
@@ -1809,32 +3789,48 @@ static int telem_any(struct rpt *myrpt, struct ast_channel *chan, const char *en
 * 4 types of telemtry are handled: Morse ID, Morse Message, Tone Sequence, and a File containing a recording.
 */
 
 * 4 types of telemtry are handled: Morse ID, Morse Message, Tone Sequence, and a File containing a recording.
 */
 
-static int telem_lookup(struct rpt *myrpt, struct ast_channel *chan, const char *node, const char *name)
+static int telem_lookup(struct rpt *myrpt,struct ast_channel *chan, char *node, char *name)
 {
 {
-       int res = 0;
+       
+       int res;
        int i;
        int i;
-       const char *entry = NULL;
-       const char *telemetry;
+       char *entry;
+       char *telemetry;
+       char *telemetry_save;
 
 
+       res = 0;
+       telemetry_save = NULL;
+       entry = NULL;
+       
        /* Retrieve the section name for telemetry from the node section */
        /* Retrieve the section name for telemetry from the node section */
-       if ((telemetry = ast_variable_retrieve(myrpt->cfg, node, TELEMETRY)))
-               entry = ast_variable_retrieve(myrpt->cfg, telemetry, name);
-
+       telemetry = (char *) ast_variable_retrieve(myrpt->cfg, node, TELEMETRY);
+       if(telemetry ){
+               telemetry_save = ast_strdup(telemetry);
+               if(!telemetry_save){
+                       ast_log(LOG_WARNING,"ast_strdup() failed in telem_lookup()\n");
+                       return res;
+               }
+               entry = (char *) ast_variable_retrieve(myrpt->cfg, telemetry_save, name);
+       }
+       
        /* Try to look up the telemetry name */ 
 
        /* Try to look up the telemetry name */ 
 
-       if (!entry) {
+       if(!entry){
                /* Telemetry name wasn't found in the config file, use the default */
                /* Telemetry name wasn't found in the config file, use the default */
-               for (i = 0; i < sizeof(tele_defs) / sizeof(struct telem_defaults); i++) {
-                       if (!strcasecmp(tele_defs[i].name, name))
+               for(i = 0; i < sizeof(tele_defs)/sizeof(struct telem_defaults) ; i++){
+                       if(!strcasecmp(tele_defs[i].name, name))
                                entry = tele_defs[i].value;
                }
        }
                                entry = tele_defs[i].value;
                }
        }
-       if (entry) {    
-               if (!ast_strlen_zero(entry))
-                       telem_any(myrpt, chan, entry);
-       } else {
+       if(entry){      
+               if(strlen(entry))
+                       if (chan) telem_any(myrpt,chan, entry);
+       }
+       else{
                res = -1;
        }
                res = -1;
        }
+       if(telemetry_save)
+               ast_free(telemetry_save);
        return res;
 }
 
        return res;
 }
 
@@ -1844,175 +3840,285 @@ static int telem_lookup(struct rpt *myrpt, struct ast_channel *chan, const char
 
 static int get_wait_interval(struct rpt *myrpt, int type)
 {
 
 static int get_wait_interval(struct rpt *myrpt, int type)
 {
-       int interval = 1000;
-       const char *wait_times = ast_variable_retrieve(myrpt->cfg, myrpt->name, "wait_times");
-
-       switch (type) {
-       case DLY_TELEM:
-               if (wait_times)
-                       interval = retrieve_astcfgint(myrpt, wait_times, "telemwait", 500, 5000, 1000);
-               break;
-       case DLY_ID:
-               if (wait_times)
-                       interval = retrieve_astcfgint(myrpt, wait_times, "idwait", 250, 5000, 500);
-               else
-                       interval = 500;
-               break;
-       case DLY_UNKEY:
-               if (wait_times)
-                       interval = retrieve_astcfgint(myrpt, wait_times, "unkeywait", 500, 5000, 1000);
-               break;
-       case DLY_CALLTERM:
-               if (wait_times)
-                       interval = retrieve_astcfgint(myrpt, wait_times, "calltermwait", 500, 5000, 1500);
-               break;
-       default:
-               return 0;
-       }
+        int interval;
+        char *wait_times;
+        char *wait_times_save;
+                                                                                                                  
+        wait_times_save = NULL;
+        wait_times = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "wait_times");
+                                                                                                                  
+        if(wait_times){
+                wait_times_save = ast_strdup(wait_times);
+                if(!wait_times_save)
+                       return 0;
+                
+        }
+                                                                                                                  
+        switch(type){
+                case DLY_TELEM:
+                        if(wait_times)
+                                interval = retrieve_astcfgint(myrpt,wait_times_save, "telemwait", 500, 5000, 1000);
+                        else
+                                interval = 1000;
+                        break;
+                                                                                                                  
+                case DLY_ID:
+                        if(wait_times)
+                                interval = retrieve_astcfgint(myrpt,wait_times_save, "idwait",250,5000,500);
+                        else
+                                interval = 500;
+                        break;
+                                                                                                                  
+                case DLY_UNKEY:
+                        if(wait_times)
+                                interval = retrieve_astcfgint(myrpt,wait_times_save, "unkeywait",50,5000,1000);
+                        else
+                                interval = 1000;
+                        break;
+                                                                                                                  
+                case DLY_LINKUNKEY:
+                        if(wait_times)
+                                interval = retrieve_astcfgint(myrpt,wait_times_save, "linkunkeywait",500,5000,1000);
+                        else
+                                interval = 1000;
+                        break;
+                                                                                                                  
+                case DLY_CALLTERM:
+                        if(wait_times)
+                                interval = retrieve_astcfgint(myrpt,wait_times_save, "calltermwait",500,5000,1500);
+                        else
+                                interval = 1500;
+                        break;
+                                                                                                                  
+                case DLY_COMP:
+                        if(wait_times)
+                                interval = retrieve_astcfgint(myrpt,wait_times_save, "compwait",500,5000,200);
+                        else
+                                interval = 200;
+                        break;
+                                                                                                                  
+                case DLY_PARROT:
+                        if(wait_times)
+                                interval = retrieve_astcfgint(myrpt,wait_times_save, "parrotwait",500,5000,200);
+                        else
+                                interval = 200;
+                        break;
+                                                                                                                  
+                default:
+                       interval = 0;
+                       break;
+        }
+       if(wait_times_save)
+                       ast_free(wait_times_save);
        return interval;
        return interval;
-}
+}                                                                                                                  
 
 
 /*
 * Wait a configurable interval of time 
 */
 
 
 /*
 * Wait a configurable interval of time 
 */
-
-
 static void wait_interval(struct rpt *myrpt, int type, struct ast_channel *chan)
 {
        int interval;
        interval = get_wait_interval(myrpt, type);
 static void wait_interval(struct rpt *myrpt, int type, struct ast_channel *chan)
 {
        int interval;
        interval = get_wait_interval(myrpt, type);
-       if (debug)
-               ast_log(LOG_NOTICE, " Delay interval = %d\n", interval);
-       if (interval)
-               ast_safe_sleep(chan, interval);
-       if (debug)
-               ast_log(LOG_NOTICE, "Delay complete\n");
+       if(debug)
+               ast_log(LOG_NOTICE,"Delay interval = %d\n", interval);
+       if(interval)
+               ast_safe_sleep(chan,interval);
+       if(debug)
+               ast_log(LOG_NOTICE,"Delay complete\n");
        return;
 }
 
        return;
 }
 
+static int split_freq(char *mhz, char *decimals, char *freq);
 
 static void *rpt_tele_thread(void *this)
 {
 
 static void *rpt_tele_thread(void *this)
 {
-       ZT_CONFINFO ci;  /* conference info */
-       int     res = 0, haslink, hastx, hasremote, imdone = 0, unkeys_queued, x;
-       struct rpt_tele *mytele = (struct rpt_tele *)this;
-       struct rpt_tele *tlist;
-       struct rpt *myrpt;
-       struct rpt_link *l, *m, linkbase;
-       struct ast_channel *mychannel;
-       const char *p, *ct;
-       struct timeval tv;
-       struct ast_tm localtm;
-#ifdef  APP_RPT_LOCK_DEBUG
-       struct lockthread *t;
+ZT_CONFINFO ci;  /* conference info */
+int    res = 0,haslink,hastx,hasremote,imdone = 0, unkeys_queued, x;
+struct rpt_tele *mytele = (struct rpt_tele *)this;
+struct  rpt_tele *tlist;
+struct rpt *myrpt;
+struct rpt_link *l,*l1,linkbase;
+struct ast_channel *mychannel;
+int id_malloc, vmajor, vminor, m;
+char *p,*ct,*ct_copy,*ident, *nodename,*cp;
+time_t t;
+#ifdef NEW_ASTERISK
+struct ast_tm localtm;
+#else
+struct tm localtm;
 #endif
 #endif
+char lbuf[MAXLINKLIST],*strs[MAXLINKLIST];
+int    i,ns,rbimode;
+char mhz[MAXREMSTR];
+char decimals[MAXREMSTR];
+char   mystr[200];
+struct zt_params par;
+
 
        /* get a pointer to myrpt */
        myrpt = mytele->rpt;
 
        /* Snag copies of a few key myrpt variables */
        rpt_mutex_lock(&myrpt->lock);
 
        /* get a pointer to myrpt */
        myrpt = mytele->rpt;
 
        /* Snag copies of a few key myrpt variables */
        rpt_mutex_lock(&myrpt->lock);
+       nodename = ast_strdup(myrpt->name);
+       if(!nodename)
+       {
+           fprintf(stderr,"rpt:Sorry unable strdup nodename\n");
+           rpt_mutex_lock(&myrpt->lock);
+           remque((struct qelem *)mytele);
+           ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
+           rpt_mutex_unlock(&myrpt->lock);
+           ast_free(mytele);
+           pthread_exit(NULL);
+       }
+
+       if (myrpt->p.ident){
+               ident = ast_strdup(myrpt->p.ident);
+               if(!ident)
+               {
+                       fprintf(stderr,"rpt:Sorry unable strdup ident\n");
+                       rpt_mutex_lock(&myrpt->lock);
+                       remque((struct qelem *)mytele);
+                       ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",
+                       __LINE__, mytele->mode); /*@@@@@@@@@@@*/
+                       rpt_mutex_unlock(&myrpt->lock);
+                       ast_free(nodename);
+                       ast_free(mytele);
+                       pthread_exit(NULL);
+               }
+               else{
+                       id_malloc = 1;
+               }
+       }
+       else
+       {
+               ident = "";
+               id_malloc = 0;
+       }
        rpt_mutex_unlock(&myrpt->lock);
        rpt_mutex_unlock(&myrpt->lock);
-       
+               
+
+
        /* allocate a pseudo-channel thru asterisk */
        /* allocate a pseudo-channel thru asterisk */
-       mychannel = ast_request("zap", AST_FORMAT_SLINEAR, "pseudo", NULL);
-       if (!mychannel) {
-               ast_log(LOG_WARNING, "rpt: unable to obtain pseudo channel\n");
+       mychannel = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
+       if (!mychannel)
+       {
+               fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
                rpt_mutex_lock(&myrpt->lock);
                remque((struct qelem *)mytele);
                rpt_mutex_lock(&myrpt->lock);
                remque((struct qelem *)mytele);
-               ast_log(LOG_NOTICE, "Telemetry thread aborted at line %d, mode: %d\n", __LINE__, mytele->mode); /*@@@@@@@@@@@*/
+               ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
                rpt_mutex_unlock(&myrpt->lock);
                rpt_mutex_unlock(&myrpt->lock);
-               ast_free(mytele);
+               ast_free(nodename);
+               if(id_malloc)
+                       ast_free(ident);
+               ast_free(mytele);               
                pthread_exit(NULL);
        }
                pthread_exit(NULL);
        }
+#ifdef AST_CDR_FLAG_POST_DISABLED
+       if (mychannel->cdr) 
+               ast_set_flag(mychannel->cdr,AST_CDR_FLAG_POST_DISABLED);
+#endif
        rpt_mutex_lock(&myrpt->lock);
        rpt_mutex_lock(&myrpt->lock);
-       mytele->chan = mychannel; /* Save a copy of the channel so we can access it externally if need be */
+       mytele->chan = mychannel;
        rpt_mutex_unlock(&myrpt->lock);
        rpt_mutex_unlock(&myrpt->lock);
-       
+
+       while((mytele->mode != SETREMOTE) && (mytele->mode != UNKEY) &&
+               (mytele->mode != LINKUNKEY))
+       {       
+                rpt_mutex_lock(&myrpt->lock);
+               if (!myrpt->active_telem)
+               {
+                       myrpt->active_telem = mytele;
+                       rpt_mutex_unlock(&myrpt->lock);
+                       break;
+               }
+                rpt_mutex_unlock(&myrpt->lock);
+               usleep(100000);
+       }
+
        /* make a conference for the tx */
        ci.chan = 0;
        /* make a conference for the tx */
        ci.chan = 0;
-       /* If there's an ID queued, or tail message queued, */
+       /* If the telemetry is only intended for a local audience, */
        /* only connect the ID audio to the local tx conference so */
        /* linked systems can't hear it */
        ci.confno = (((mytele->mode == ID) || (mytele->mode == IDTALKOVER) || (mytele->mode == UNKEY) || 
        /* only connect the ID audio to the local tx conference so */
        /* linked systems can't hear it */
        ci.confno = (((mytele->mode == ID) || (mytele->mode == IDTALKOVER) || (mytele->mode == UNKEY) || 
-               (mytele->mode == TAILMSG)) ?
+               (mytele->mode == TAILMSG) || (mytele->mode == LINKUNKEY) || (mytele->mode == TIMEOUT) || 
+               (mytele->mode == PARROT) || (mytele->mode == STATS_TIME_LOCAL)) ? 
                        myrpt->txconf : myrpt->conf);
        ci.confmode = ZT_CONF_CONFANN;
        /* first put the channel on the conference in announce mode */
                        myrpt->txconf : myrpt->conf);
        ci.confmode = ZT_CONF_CONFANN;
        /* first put the channel on the conference in announce mode */
-       if (ioctl(mychannel->fds[0], ZT_SETCONF, &ci) == -1) {
+       if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
+       {
                ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
                rpt_mutex_lock(&myrpt->lock);
                ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
                rpt_mutex_lock(&myrpt->lock);
+               myrpt->active_telem = NULL;
                remque((struct qelem *)mytele);
                rpt_mutex_unlock(&myrpt->lock);
                remque((struct qelem *)mytele);
                rpt_mutex_unlock(&myrpt->lock);
-               ast_log(LOG_NOTICE, "Telemetry thread aborted at line %d, mode: %d\n", __LINE__, mytele->mode); /*@@@@@@@@@@@*/
-               ast_free(mytele);
+               ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
+               ast_free(nodename);
+               if(id_malloc)
+                       ast_free(ident);
+               ast_free(mytele);               
                ast_hangup(mychannel);
                pthread_exit(NULL);
        }
        ast_stopstream(mychannel);
                ast_hangup(mychannel);
                pthread_exit(NULL);
        }
        ast_stopstream(mychannel);
-       switch (mytele->mode) {
-       case ID:
-       case ID1:
+       switch(mytele->mode)
+       {
+           case ID:
+           case ID1:
                /* wait a bit */
                /* wait a bit */
-               wait_interval(myrpt, (mytele->mode == ID) ? DLY_ID : DLY_TELEM, mychannel);
-               res = telem_any(myrpt, mychannel, myrpt->p.ident); 
+               wait_interval(myrpt, (mytele->mode == ID) ? DLY_ID : DLY_TELEM,mychannel);
+               res = telem_any(myrpt,mychannel, ident); 
                imdone=1;       
                break;
                
                imdone=1;       
                break;
                
-       case TAILMSG:
-               res = ast_streamfile(mychannel, myrpt->p.tailmsg.msgs[myrpt->tailmessagen], mychannel->language); 
+           case TAILMSG:
+               res = ast_streamfile(mychannel, myrpt->p.tailmessages[myrpt->tailmessagen], mychannel->language); 
                break;
                
                break;
                
-       case IDTALKOVER:
-               p = ast_variable_retrieve(myrpt->cfg, myrpt->name, "idtalkover");
-               if (p)
-                       res = telem_any(myrpt, mychannel, p); 
-               imdone = 1;     
-               break;
-       case PROC:
+           case IDTALKOVER:
+               p = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "idtalkover");
+               if(p)
+                       res = telem_any(myrpt,mychannel, p); 
+               imdone=1;       
+               break;
+                       
+           case PROC:
                /* wait a little bit longer */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = telem_lookup(myrpt, mychannel, myrpt->name, "patchup");
                /* wait a little bit longer */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = telem_lookup(myrpt, mychannel, myrpt->name, "patchup");
-               if (res < 0) { /* Then default message */
+               if(res < 0){ /* Then default message */
                        res = ast_streamfile(mychannel, "rpt/callproceeding", mychannel->language);
                }
                break;
                        res = ast_streamfile(mychannel, "rpt/callproceeding", mychannel->language);
                }
                break;
-       case TERM:
+           case TERM:
                /* wait a little bit longer */
                wait_interval(myrpt, DLY_CALLTERM, mychannel);
                res = telem_lookup(myrpt, mychannel, myrpt->name, "patchdown");
                /* wait a little bit longer */
                wait_interval(myrpt, DLY_CALLTERM, mychannel);
                res = telem_lookup(myrpt, mychannel, myrpt->name, "patchdown");
-               if (res < 0) { /* Then default message */
+               if(res < 0){ /* Then default message */
                        res = ast_streamfile(mychannel, "rpt/callterminated", mychannel->language);
                }
                break;
                        res = ast_streamfile(mychannel, "rpt/callterminated", mychannel->language);
                }
                break;
-       case COMPLETE:
+           case COMPLETE:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
-               res = telem_lookup(myrpt, mychannel, myrpt->name, "functcomplete");
+               res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
                break;
                break;
-       case MACRO_NOTFOUND:
+           case MACRO_NOTFOUND:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/macro_notfound", mychannel->language);
                break;
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/macro_notfound", mychannel->language);
                break;
-       case GOSUB_NOTFOUND:
-               /* wait a little bit */
-               wait_interval(myrpt, DLY_TELEM, mychannel);
-               res = ast_streamfile(mychannel, "rpt/gosub_notfound", mychannel->language);
-               break;
-       case MACRO_BUSY:
+           case MACRO_BUSY:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/macro_busy", mychannel->language);
                break;
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/macro_busy", mychannel->language);
                break;
-       case GOSUB_BUSY:
-               /* wait a little bit */
-               wait_interval(myrpt, DLY_TELEM, mychannel);
-               res = ast_streamfile(mychannel, "rpt/gosub_busy", mychannel->language);
-               break;
-       case UNKEY:
-               if (myrpt->patchnoct && myrpt->callmode) { /* If no CT during patch configured, then don't send one */
+           case UNKEY:
+               if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
                        imdone = 1;
                        break;
                }
                        imdone = 1;
                        break;
                }
@@ -2032,31 +4138,32 @@ static void *rpt_tele_thread(void *this)
 
                tlist = myrpt->tele.next;
                unkeys_queued = 0;
 
                tlist = myrpt->tele.next;
                unkeys_queued = 0;
-               if (tlist != &myrpt->tele) {
-                       rpt_mutex_lock(&myrpt->lock);
-                       while (tlist != &myrpt->tele) {
-                               if (tlist->mode == UNKEY)
-                                       unkeys_queued++;
-                               tlist = tlist->next;
-                       }
-                       rpt_mutex_unlock(&myrpt->lock);
-               }
-               if (unkeys_queued > 1) {
+                if (tlist != &myrpt->tele)
+                {
+                        rpt_mutex_lock(&myrpt->lock);
+                        while(tlist != &myrpt->tele){
+                                if (tlist->mode == UNKEY) unkeys_queued++;
+                                tlist = tlist->next;
+                        }
+                        rpt_mutex_unlock(&myrpt->lock);
+               }
+               if( unkeys_queued > 1){
                        imdone = 1;
                        break;
                }
 
                /* Wait for the telemetry timer to expire */
                /* Periodically check the timer since it can be re-initialized above */
                        imdone = 1;
                        break;
                }
 
                /* Wait for the telemetry timer to expire */
                /* Periodically check the timer since it can be re-initialized above */
-               while (myrpt->unkeytocttimer) {
+               while(myrpt->unkeytocttimer)
+               {
                        int ctint;
                        int ctint;
-                       if (myrpt->unkeytocttimer > 100)
+                       if(myrpt->unkeytocttimer > 100)
                                ctint = 100;
                        else
                                ctint = myrpt->unkeytocttimer;
                        ast_safe_sleep(mychannel, ctint);
                        rpt_mutex_lock(&myrpt->lock);
                                ctint = 100;
                        else
                                ctint = myrpt->unkeytocttimer;
                        ast_safe_sleep(mychannel, ctint);
                        rpt_mutex_lock(&myrpt->lock);
-                       if (myrpt->unkeytocttimer < ctint)
+                       if(myrpt->unkeytocttimer < ctint)
                                myrpt->unkeytocttimer = 0;
                        else
                                myrpt->unkeytocttimer -= ctint;
                                myrpt->unkeytocttimer = 0;
                        else
                                myrpt->unkeytocttimer -= ctint;
@@ -2067,7 +4174,7 @@ static void *rpt_tele_thread(void *this)
                * Now, the carrier on the rptr rx should be gone. 
                * If it re-appeared, then forget about sending the CT
                */
                * Now, the carrier on the rptr rx should be gone. 
                * If it re-appeared, then forget about sending the CT
                */
-               if (myrpt->keyed) {
+               if(myrpt->keyed){
                        imdone = 1;
                        break;
                }
                        imdone = 1;
                        break;
                }
@@ -2081,143 +4188,609 @@ static void *rpt_tele_thread(void *this)
                hastx = 0;
                hasremote = 0;          
                l = myrpt->links.next;
                hastx = 0;
                hasremote = 0;          
                l = myrpt->links.next;
-               if (l != &myrpt->links) {
+               if (l != &myrpt->links)
+               {
                        rpt_mutex_lock(&myrpt->lock);
                        rpt_mutex_lock(&myrpt->lock);
-                       while (l != &myrpt->links) {
-                               if (l->name[0] == '0') {
+                       while(l != &myrpt->links)
+                       {
+                               if (l->name[0] == '0')
+                               {
                                        l = l->next;
                                        continue;
                                }
                                haslink = 1;
                                if (l->mode) {
                                        hastx++;
                                        l = l->next;
                                        continue;
                                }
                                haslink = 1;
                                if (l->mode) {
                                        hastx++;
-                                       if (l->isremote)
-                                               hasremote++;
+                                       if (l->isremote) hasremote++;
                                }
                                l = l->next;
                        }
                        rpt_mutex_unlock(&myrpt->lock);
                }
                                }
                                l = l->next;
                        }
                        rpt_mutex_unlock(&myrpt->lock);
                }
-               if (haslink) {
-                       res = telem_lookup(myrpt, mychannel, myrpt->name, (!hastx) ? "remotemon" : "remotetx");
-                       if (res)
-                               ast_log(LOG_WARNING, "telem_lookup:remotexx failed on %s\n", mychannel->name);
+               if (haslink)
+               {
 
 
+                       res = telem_lookup(myrpt,mychannel, myrpt->name, (!hastx) ? "remotemon" : "remotetx");
+                       if(res)
+                               ast_log(LOG_WARNING, "telem_lookup:remotexx failed on %s\n", mychannel->name);
+                       
+               
                        /* if in remote cmd mode, indicate it */
                        /* if in remote cmd mode, indicate it */
-                       if (myrpt->cmdnode[0]) {
-                               ast_safe_sleep(mychannel, 200);
-                               res = telem_lookup(myrpt, mychannel, myrpt->name, "cmdmode");
-                               if (res)
+                       if (myrpt->cmdnode[0])
+                       {
+                               ast_safe_sleep(mychannel,200);
+                               res = telem_lookup(myrpt,mychannel, myrpt->name, "cmdmode");
+                               if(res)
                                        ast_log(LOG_WARNING, "telem_lookup:cmdmode failed on %s\n", mychannel->name);
                                ast_stopstream(mychannel);
                        }
                                        ast_log(LOG_WARNING, "telem_lookup:cmdmode failed on %s\n", mychannel->name);
                                ast_stopstream(mychannel);
                        }
-               } else if ((ct = ast_variable_retrieve(myrpt->cfg, myrpt->name, "unlinkedct"))) { /* Unlinked Courtesy Tone */
-                       res = telem_lookup(myrpt, mychannel, myrpt->name, ct);
-                       if (res)
+               }
+               else if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "unlinkedct"))){ /* Unlinked Courtesy Tone */
+                       ct_copy = ast_strdup(ct);
+                       if(ct_copy)
+                       {
+                               res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
+                               ast_free(ct_copy);
+                       }
+                       else
+                               res = -1;
+                       if(res)
                                ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
                }       
                                ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
                }       
-               if (hasremote && (!myrpt->cmdnode[0])) {
+               if (hasremote && (!myrpt->cmdnode[0]))
+               {
                        /* set for all to hear */
                        ci.chan = 0;
                        ci.confno = myrpt->conf;
                        ci.confmode = ZT_CONF_CONFANN;
                        /* first put the channel on the conference in announce mode */
                        /* set for all to hear */
                        ci.chan = 0;
                        ci.confno = myrpt->conf;
                        ci.confmode = ZT_CONF_CONFANN;
                        /* first put the channel on the conference in announce mode */
-                       if (ioctl(mychannel->fds[0], ZT_SETCONF, &ci) == -1) {
+                       if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
+                       {
                                ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
                                rpt_mutex_lock(&myrpt->lock);
                                ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
                                rpt_mutex_lock(&myrpt->lock);
+                               myrpt->active_telem = NULL;
                                remque((struct qelem *)mytele);
                                rpt_mutex_unlock(&myrpt->lock);
                                remque((struct qelem *)mytele);
                                rpt_mutex_unlock(&myrpt->lock);
-                               ast_log(LOG_NOTICE, "Telemetry thread aborted at line %d, mode: %d\n", __LINE__, mytele->mode); /*@@@@@@@@@@@*/
-                               ast_free(mytele);
+                               ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
+                               ast_free(nodename);
+                               if(id_malloc)
+                                       ast_free(ident);
+                               ast_free(mytele);               
                                ast_hangup(mychannel);
                                pthread_exit(NULL);
                        }
                                ast_hangup(mychannel);
                                pthread_exit(NULL);
                        }
-                       if ((ct = ast_variable_retrieve(myrpt->cfg, myrpt->name, "remotect"))) { /* Unlinked Courtesy Tone */
-                               ast_safe_sleep(mychannel, 200);
-                               res = telem_lookup(myrpt, mychannel, myrpt->name, ct);
-                               if (res)
+                       if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "remotect"))){ /* Unlinked Courtesy Tone */
+                               ast_safe_sleep(mychannel,200);
+                               ct_copy = ast_strdup(ct);
+                               if(ct_copy)
+                               {
+                                       res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
+                                       ast_free(ct_copy);
+                               }
+                               else
+                                       res = -1;
+               
+                               if(res)
                                        ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
                        }       
                }
                                        ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
                        }       
                }
-#ifdef _MDC_DECODE_H_
-               if (myrpt->lastunit) {
-                       char mystr[10];
+#if    defined(_MDC_DECODE_H_) && defined(MDC_SAY_WHEN_DOING_CT)
+               if (myrpt->lastunit)
+               {
+                       char mystr[10];
+
+                       ast_safe_sleep(mychannel,200);
+                       /* set for all to hear */
+                       ci.chan = 0;
+                       ci.confno = myrpt->txconf;
+                       ci.confmode = ZT_CONF_CONFANN;
+                       /* first put the channel on the conference in announce mode */
+                       if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
+                       {
+                               ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
+                               rpt_mutex_lock(&myrpt->lock);
+                               myrpt->active_telem = NULL;
+                               remque((struct qelem *)mytele);
+                               rpt_mutex_unlock(&myrpt->lock);
+                               ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
+                               ast_free(nodename);
+                               if(id_malloc)
+                                       ast_free(ident);
+                               ast_free(mytele);               
+                               ast_hangup(mychannel);
+                               pthread_exit(NULL);
+                       }
+                       sprintf(mystr,"%04x",myrpt->lastunit);
+                       myrpt->lastunit = 0;
+                       ast_say_character_str(mychannel,mystr,NULL,mychannel->language);
+                       break;
+               }
+#endif
+               imdone = 1;
+               break;
+           case LINKUNKEY:
+               if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
+                       imdone = 1;
+                       break;
+               }
+                       
+               /*
+               * Reset the Unkey to CT timer
+               */
+
+               x = get_wait_interval(myrpt, DLY_LINKUNKEY);
+               mytele->mylink.linkunkeytocttimer = x; /* Must be protected as it is changed below */
+
+               /*
+               * If there's one already queued, don't do another
+               */
+
+               tlist = myrpt->tele.next;
+               unkeys_queued = 0;
+                if (tlist != &myrpt->tele)
+                {
+                        rpt_mutex_lock(&myrpt->lock);
+                        while(tlist != &myrpt->tele){
+                                if (tlist->mode == LINKUNKEY) unkeys_queued++;
+                                tlist = tlist->next;
+                        }
+                        rpt_mutex_unlock(&myrpt->lock);
+               }
+               if( unkeys_queued > 1){
+                       imdone = 1;
+                       break;
+               }
 
 
-                       ast_safe_sleep(mychannel, 200);
-                       /* set for all to hear */
-                       ci.chan = 0;
-                       ci.confno = myrpt->txconf;
-                       ci.confmode = ZT_CONF_CONFANN;
-                       /* first put the channel on the conference in announce mode */
-                       if (ioctl(mychannel->fds[0], ZT_SETCONF, &ci) == -1) {
-                               ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
-                               rpt_mutex_lock(&myrpt->lock);
-                               remque((struct qelem *)mytele);
-                               rpt_mutex_unlock(&myrpt->lock);
-                               ast_log(LOG_NOTICE, "Telemetry thread aborted at line %d, mode: %d\n", __LINE__, mytele->mode); /*@@@@@@@@@@@*/
-                               ast_free(mytele);               
-                               ast_hangup(mychannel);
-                               pthread_exit(NULL);
-                       }
-                       snprintf(mystr, sizeof(mystr), "%04x", myrpt->lastunit);
-                       myrpt->lastunit = 0;
-                       ast_say_character_str(mychannel, mystr, NULL, mychannel->language);
-                       break;
+               /* Wait for the telemetry timer to expire */
+               /* Periodically check the timer since it can be re-initialized above */
+               while(mytele->mylink.linkunkeytocttimer)
+               {
+                       int ctint;
+                       if(mytele->mylink.linkunkeytocttimer > 100)
+                               ctint = 100;
+                       else
+                               ctint = mytele->mylink.linkunkeytocttimer;
+                       ast_safe_sleep(mychannel, ctint);
+                       rpt_mutex_lock(&myrpt->lock);
+                       if(mytele->mylink.linkunkeytocttimer < ctint)
+                               mytele->mylink.linkunkeytocttimer = 0;
+                       else
+                               mytele->mylink.linkunkeytocttimer -= ctint;
+                       rpt_mutex_unlock(&myrpt->lock);
                }
                }
-#endif
+       
+               if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "linkunkeyct"))){ /* Unlinked Courtesy Tone */
+                       ct_copy = ast_strdup(ct);
+                       if(ct_copy){
+                               res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
+                               ast_free(ct_copy);
+                       }
+                       else
+                               res = -1;
+                       if(res)
+                               ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
+               }       
                imdone = 1;
                break;
                imdone = 1;
                break;
-       case REMDISC:
+           case REMDISC:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
-               res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
+               l = myrpt->links.next;
+               haslink = 0;
+               /* dont report if a link for this one still on system */
+               if (l != &myrpt->links)
+               {
+                       rpt_mutex_lock(&myrpt->lock);
+                       while(l != &myrpt->links)
+                       {
+                               if (l->name[0] == '0')
+                               {
+                                       l = l->next;
+                                       continue;
+                               }
+                               if (!strcmp(l->name,mytele->mylink.name))
+                               {
+                                       haslink = 1;
+                                       break;
+                               }
+                               l = l->next;
+                       }
+                       rpt_mutex_unlock(&myrpt->lock);
+               }
+               if (haslink)
+               {
+                       imdone = 1;
+                       break;
+               }
+               res = saynode(myrpt,mychannel,mytele->mylink.name);
                if (!res) 
                if (!res) 
-                       res = ast_waitstream(mychannel, "");
-               else
-                        ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
-               ast_stopstream(mychannel);
-               ast_say_character_str(mychannel, mytele->mylink.name, NULL, mychannel->language);
-               res = ast_streamfile(mychannel, ((mytele->mylink.connected) ? 
+                   res = ast_streamfile(mychannel, ((mytele->mylink.hasconnected) ? 
                        "rpt/remote_disc" : "rpt/remote_busy"), mychannel->language);
                break;
                        "rpt/remote_disc" : "rpt/remote_busy"), mychannel->language);
                break;
-       case REMALREADY:
+           case REMALREADY:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/remote_already", mychannel->language);
                break;
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/remote_already", mychannel->language);
                break;
-       case REMNOTFOUND:
+           case REMNOTFOUND:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/remote_notfound", mychannel->language);
                break;
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/remote_notfound", mychannel->language);
                break;
-       case REMGO:
+           case REMGO:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/remote_go", mychannel->language);
                break;
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                res = ast_streamfile(mychannel, "rpt/remote_go", mychannel->language);
                break;
-       case CONNECTED:
+           case CONNECTED:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM,  mychannel);
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM,  mychannel);
-               res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
+               res = saynode(myrpt,mychannel,mytele->mylink.name);
+               if (!res)
+                   res = ast_streamfile(mychannel, "rpt/connected", mychannel->language);
                if (!res) 
                        res = ast_waitstream(mychannel, "");
                else
                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                ast_stopstream(mychannel);
                if (!res) 
                        res = ast_waitstream(mychannel, "");
                else
                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                ast_stopstream(mychannel);
-               ast_say_character_str(mychannel, mytele->mylink.name, NULL, mychannel->language);
-               res = ast_streamfile(mychannel, "rpt/connected", mychannel->language);
-               break;
-       case CONNFAIL:
-               res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
+               res = ast_streamfile(mychannel, "digits/2", mychannel->language);
                if (!res) 
                        res = ast_waitstream(mychannel, "");
                else
                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                ast_stopstream(mychannel);
                if (!res) 
                        res = ast_waitstream(mychannel, "");
                else
                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                ast_stopstream(mychannel);
-               ast_say_character_str(mychannel, mytele->mylink.name, NULL, mychannel->language);
-               res = ast_streamfile(mychannel, "rpt/connection_failed", mychannel->language);
+               res = saynode(myrpt,mychannel,myrpt->name);
+               imdone = 1;
+               break;
+           case CONNFAIL:
+               res = saynode(myrpt,mychannel,mytele->mylink.name);
+               if (!res) 
+                   res = ast_streamfile(mychannel, "rpt/connection_failed", mychannel->language);
+               break;
+           case MEMNOTFOUND:
+               /* wait a little bit */
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               res = ast_streamfile(mychannel, "rpt/memory_notfound", mychannel->language);
+               break;
+           case PLAYBACK:
+               /* wait a little bit */
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               res = ast_streamfile(mychannel, mytele->param, mychannel->language);
+               break;
+           case TOPKEY:
+               /* wait a little bit */
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               for(i = 0; i < TOPKEYN; i++)
+               {
+                       if (!myrpt->topkey[i].node[0]) continue;
+                       if ((!myrpt->topkeylong) && (myrpt->topkey[i].keyed)) continue;
+                       res = saynode(myrpt, mychannel, myrpt->topkey[i].node);
+                       if (!res) res = sayfile(mychannel,(myrpt->topkey[i].keyed) ?
+                               "rpt/keyedfor" : "rpt/unkeyedfor");
+                       if (!res) res = saynum(mychannel,
+                               myrpt->topkey[i].timesince);
+                       if (!res) res = sayfile(mychannel,"rpt/seconds");
+                       if (!myrpt->topkeylong) break;
+               }
+               imdone = 1;
+               break;
+           case SETREMOTE:
+               ast_mutex_lock(&myrpt->remlock);
+               res = 0;
+               if(!strcmp(myrpt->remoterig, remote_rig_ft897))
+               {
+                       res = set_ft897(myrpt);
+               }
+               else if(!strcmp(myrpt->remoterig, remote_rig_tm271))
+               {
+                       res = set_tm271(myrpt);
+               }
+               else if(!strcmp(myrpt->remoterig, remote_rig_ic706))
+               {
+                       res = set_ic706(myrpt);
+               }
+               else if(!strcmp(myrpt->remoterig, remote_rig_rbi)||!strcmp(myrpt->remoterig, remote_rig_ppp16))
+               {
+                       if (ioperm(myrpt->p.iobase,1,1) == -1)
+                       {
+                               rpt_mutex_unlock(&myrpt->lock);
+                               ast_log(LOG_WARNING, "Cant get io permission on IO port %x hex\n",myrpt->p.iobase);
+                               res = -1;
+                       }
+                       else res = setrbi(myrpt);
+               }
+               else if(!strcmp(myrpt->remoterig, remote_rig_kenwood))
+               {
+                       if (myrpt->iofd >= 0) setdtr(myrpt->iofd,1);
+                       res = setkenwood(myrpt);
+                       if (myrpt->iofd >= 0) setdtr(myrpt->iofd,0);
+                       if (ast_safe_sleep(mychannel,200) == -1)
+                       {
+                               ast_mutex_unlock(&myrpt->remlock);
+                               res = -1;
+                               break;
+                       }
+                       if (myrpt->iofd < 0)
+                       {
+                               i = ZT_FLUSH_EVENT;
+                               if (ioctl(myrpt->zaptxchannel->fds[0],ZT_FLUSH,&i) == -1)
+                               {
+                                       ast_mutex_unlock(&myrpt->remlock);
+                                       ast_log(LOG_ERROR,"Cant flush events");
+                                       res = -1;
+                                       break;
+                               }
+                               if (ioctl(myrpt->zaprxchannel->fds[0],ZT_GET_PARAMS,&par) == -1)
+                               {
+                                       ast_mutex_unlock(&myrpt->remlock);
+                                       ast_log(LOG_ERROR,"Cant get params");
+                                       res = -1;
+                                       break;
+                               }
+                               myrpt->remoterx = 
+                                       (par.rxisoffhook || (myrpt->tele.next != &myrpt->tele));
+                       }
+               }
+
+               ast_mutex_unlock(&myrpt->remlock);
+               if (!res)
+               {
+                       imdone = 1;
+                       break;
+               }
+               /* fall thru to invalid freq */
+           case INVFREQ:
+               /* wait a little bit */
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               res = ast_streamfile(mychannel, "rpt/invalid-freq", mychannel->language);
+               break;
+           case REMMODE:
+               cp = 0;
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               switch(myrpt->remmode)
+               {
+                   case REM_MODE_FM:
+                       saycharstr(mychannel,"FM");
+                       break;
+                   case REM_MODE_USB:
+                       saycharstr(mychannel,"USB");
+                       break;
+                   case REM_MODE_LSB:
+                       saycharstr(mychannel,"LSB");
+                       break;
+                   case REM_MODE_AM:
+                       saycharstr(mychannel,"AM");
+                       break;
+               }
+               wait_interval(myrpt, DLY_COMP, mychannel);
+               if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
+               break;
+           case LOGINREQ:
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               sayfile(mychannel,"rpt/login");
+               saycharstr(mychannel,myrpt->name);
+               break;
+           case REMLOGIN:
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               saycharstr(mychannel,myrpt->loginuser);
+               saynode(myrpt,mychannel,myrpt->name);
+               wait_interval(myrpt, DLY_COMP, mychannel);
+               if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
+               break;
+           case REMXXX:
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               res = 0;
+               switch(mytele->submode)
+               {
+                   case 100: /* RX PL Off */
+                       sayfile(mychannel, "rpt/rxpl");
+                       sayfile(mychannel, "rpt/off");
+                       break;
+                   case 101: /* RX PL On */
+                       sayfile(mychannel, "rpt/rxpl");
+                       sayfile(mychannel, "rpt/on");
+                       break;
+                   case 102: /* TX PL Off */
+                       sayfile(mychannel, "rpt/txpl");
+                       sayfile(mychannel, "rpt/off");
+                       break;
+                   case 103: /* TX PL On */
+                       sayfile(mychannel, "rpt/txpl");
+                       sayfile(mychannel, "rpt/on");
+                       break;
+                   case 104: /* Low Power */
+                       sayfile(mychannel, "rpt/lopwr");
+                       break;
+                   case 105: /* Medium Power */
+                       sayfile(mychannel, "rpt/medpwr");
+                       break;
+                   case 106: /* Hi Power */
+                       sayfile(mychannel, "rpt/hipwr");
+                       break;
+                   case 113: /* Scan down slow */
+                       sayfile(mychannel,"rpt/down");
+                       sayfile(mychannel, "rpt/slow");
+                       break;
+                   case 114: /* Scan down quick */
+                       sayfile(mychannel,"rpt/down");
+                       sayfile(mychannel, "rpt/quick");
+                       break;
+                   case 115: /* Scan down fast */
+                       sayfile(mychannel,"rpt/down");
+                       sayfile(mychannel, "rpt/fast");
+                       break;
+                   case 116: /* Scan up slow */
+                       sayfile(mychannel,"rpt/up");
+                       sayfile(mychannel, "rpt/slow");
+                       break;
+                   case 117: /* Scan up quick */
+                       sayfile(mychannel,"rpt/up");
+                       sayfile(mychannel, "rpt/quick");
+                       break;
+                   case 118: /* Scan up fast */
+                       sayfile(mychannel,"rpt/up");
+                       sayfile(mychannel, "rpt/fast");
+                       break;
+                   default:
+                       res = -1;
+               }
+               wait_interval(myrpt, DLY_COMP, mychannel);
+               if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
+               break;
+           case SCAN:
+               ast_mutex_lock(&myrpt->remlock);
+               if (myrpt->hfscanstop)
+               {
+                       myrpt->hfscanstatus = 0;
+                       myrpt->hfscanmode = 0;
+                       myrpt->hfscanstop = 0;
+                       mytele->mode = SCANSTAT;
+                       ast_mutex_unlock(&myrpt->remlock);
+                       if (ast_safe_sleep(mychannel,1000) == -1) break;
+                       sayfile(mychannel, "rpt/stop"); 
+                       imdone = 1;
+                       break;
+               }
+               if (myrpt->hfscanstatus > -2) service_scan(myrpt);
+               i = myrpt->hfscanstatus;
+               myrpt->hfscanstatus = 0;
+               if (i) mytele->mode = SCANSTAT;
+               ast_mutex_unlock(&myrpt->remlock);
+               if (i < 0) sayfile(mychannel, "rpt/stop"); 
+               else if (i > 0) saynum(mychannel,i);
+               imdone = 1;
+               break;
+           case TUNE:
+               ast_mutex_lock(&myrpt->remlock);
+               if (!strcmp(myrpt->remoterig,remote_rig_ic706))
+               {
+                       set_mode_ic706(myrpt, REM_MODE_AM);
+                       if(play_tone(mychannel, 800, 6000, 8192) == -1) break;
+                       ast_safe_sleep(mychannel,500);
+                       set_mode_ic706(myrpt, myrpt->remmode);
+                       myrpt->tunerequest = 0;
+                       ast_mutex_unlock(&myrpt->remlock);
+                       imdone = 1;
+                       break;
+               }
+               set_mode_ft897(myrpt, REM_MODE_AM);
+               simple_command_ft897(myrpt, 8);
+               if(play_tone(mychannel, 800, 6000, 8192) == -1) break;
+               simple_command_ft897(myrpt, 0x88);
+               ast_safe_sleep(mychannel,500);
+               set_mode_ft897(myrpt, myrpt->remmode);
+               myrpt->tunerequest = 0;
+               ast_mutex_unlock(&myrpt->remlock);
+               imdone = 1;
+               break;
+           case REMSHORTSTATUS:
+           case REMLONGSTATUS: 
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               res = saynode(myrpt,mychannel,myrpt->name);
+               if(!res)
+                       res = sayfile(mychannel,"rpt/frequency");
+               if(!res)
+                       res = split_freq(mhz, decimals, myrpt->freq);
+               if (!multimode_capable(myrpt)) decimals[3] = 0;
+               if(!res){
+                       m = atoi(mhz);
+                       if(m < 100)
+                               res = saynum(mychannel, m);
+                       else
+                               res = saycharstr(mychannel, mhz);
+               }
+               if(!res)
+                       res = sayfile(mychannel, "letters/dot");
+               if(!res)
+                       res = saycharstr(mychannel, decimals);
+       
+               if(res) break;
+               if(myrpt->remmode == REM_MODE_FM){ /* Mode FM? */
+                       switch(myrpt->offset){
+       
+                               case REM_MINUS:
+                                       res = sayfile(mychannel,"rpt/minus");
+                                       break;
+                               
+                               case REM_SIMPLEX:
+                                       res = sayfile(mychannel,"rpt/simplex");
+                                       break;
+                                       
+                               case REM_PLUS:
+                                       res = sayfile(mychannel,"rpt/plus");
+                                       break;
+                                       
+                               default:
+                                       break;
+                       }
+               }
+               else{ /* Must be USB, LSB, or AM */
+                       switch(myrpt->remmode){
+
+                               case REM_MODE_USB:
+                                       res = saycharstr(mychannel, "USB");
+                                       break;
+
+                               case REM_MODE_LSB:
+                                       res = saycharstr(mychannel, "LSB");
+                                       break;
+
+                               case REM_MODE_AM:
+                                       res = saycharstr(mychannel, "AM");
+                                       break;
+
+
+                               default:
+                                       break;
+                       }
+               }
+
+               if (res == -1) break;
+
+               if(mytele->mode == REMSHORTSTATUS){ /* Short status? */
+                       wait_interval(myrpt, DLY_COMP, mychannel);
+                       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
+                       break;
+               }
+
+               if (strcmp(myrpt->remoterig,remote_rig_ic706))
+               {
+                       switch(myrpt->powerlevel){
+
+                               case REM_LOWPWR:
+                                       res = sayfile(mychannel,"rpt/lopwr") ;
+                                       break;
+                               case REM_MEDPWR:
+                                       res = sayfile(mychannel,"rpt/medpwr");
+                                       break;
+                               case REM_HIPWR:
+                                       res = sayfile(mychannel,"rpt/hipwr"); 
+                                       break;
+                               }
+               }
+
+               rbimode = ((!strncmp(myrpt->remoterig,remote_rig_rbi,3))
+                 || (!strncmp(myrpt->remoterig,remote_rig_ic706,3)));
+               if (res || (sayfile(mychannel,"rpt/rxpl") == -1)) break;
+               if (rbimode && (sayfile(mychannel,"rpt/txpl") == -1)) break;
+               if ((sayfile(mychannel,"rpt/frequency") == -1) ||
+                       (saycharstr(mychannel,myrpt->rxpl) == -1)) break;
+               if ((!rbimode) && ((sayfile(mychannel,"rpt/txpl") == -1) ||
+                       (sayfile(mychannel,"rpt/frequency") == -1) ||
+                       (saycharstr(mychannel,myrpt->txpl) == -1))) break;
+               if(myrpt->remmode == REM_MODE_FM){ /* Mode FM? */
+                       if ((sayfile(mychannel,"rpt/rxpl") == -1) ||
+                               (sayfile(mychannel,((myrpt->rxplon) ? "rpt/on" : "rpt/off")) == -1) ||
+                               (sayfile(mychannel,"rpt/txpl") == -1) ||
+                               (sayfile(mychannel,((myrpt->txplon) ? "rpt/on" : "rpt/off")) == -1))
+                               {
+                                       break;
+                               }
+               }
+               wait_interval(myrpt, DLY_COMP, mychannel);
+               if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
                break;
                break;
-       case STATUS:
+           case STATUS:
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                hastx = 0;
                /* wait a little bit */
                wait_interval(myrpt, DLY_TELEM, mychannel);
                hastx = 0;
@@ -2226,73 +4799,132 @@ static void *rpt_tele_thread(void *this)
                rpt_mutex_lock(&myrpt->lock);
                /* make our own list of links */
                l = myrpt->links.next;
                rpt_mutex_lock(&myrpt->lock);
                /* make our own list of links */
                l = myrpt->links.next;
-               while (l != &myrpt->links) {
-                       if (l->name[0] == '0') {
+               while(l != &myrpt->links)
+               {
+                       if (l->name[0] == '0')
+                       {
                                l = l->next;
                                continue;
                        }
                                l = l->next;
                                continue;
                        }
-                       m = ast_malloc(sizeof(*m));
-                       if (!m) {
+                       l1 = ast_malloc(sizeof(struct rpt_link));
+                       if (!l1)
+                       {
                                ast_log(LOG_WARNING, "Cannot alloc memory on %s\n", mychannel->name);
                                remque((struct qelem *)mytele);
                                ast_log(LOG_WARNING, "Cannot alloc memory on %s\n", mychannel->name);
                                remque((struct qelem *)mytele);
+                               myrpt->active_telem = NULL;
                                rpt_mutex_unlock(&myrpt->lock);
                                rpt_mutex_unlock(&myrpt->lock);
-                               ast_log(LOG_NOTICE, "Telemetry thread aborted at line %d, mode: %d\n", __LINE__, mytele->mode); /*@@@@@@@@@@@*/
-                               ast_free(mytele);
+                               ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
+                               ast_free(nodename);
+                               if(id_malloc)
+                                       ast_free(ident);
+                               ast_free(mytele);               
                                ast_hangup(mychannel);
                                pthread_exit(NULL);
                        }
                                ast_hangup(mychannel);
                                pthread_exit(NULL);
                        }
-                       memcpy(m, l, sizeof(struct rpt_link));
-                       m->next = m->prev = NULL;
-                       insque((struct qelem *)m, (struct qelem *)linkbase.next);
+                       memcpy(l1,l,sizeof(struct rpt_link));
+                       l1->next = l1->prev = NULL;
+                       insque((struct qelem *)l1,(struct qelem *)linkbase.next);
                        l = l->next;
                }
                rpt_mutex_unlock(&myrpt->lock);
                        l = l->next;
                }
                rpt_mutex_unlock(&myrpt->lock);
-               res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
-               if (!res)
-                       res = ast_waitstream(mychannel, "");
-               else
-                        ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
-               ast_stopstream(mychannel);
-               ast_say_character_str(mychannel, myrpt->name, NULL, mychannel->language);
-               if (!res) 
-                       res = ast_waitstream(mychannel, "");
-               else
-                        ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
-               ast_stopstream(mychannel);
-               if (myrpt->callmode) {
+               res = saynode(myrpt,mychannel,myrpt->name);
+               if (myrpt->callmode)
+               {
                        hastx = 1;
                        res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
                        hastx = 1;
                        res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
-                       if (!res)
+                       if (!res) 
                                res = ast_waitstream(mychannel, "");
                        else
                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
                }
                l = linkbase.next;
                                res = ast_waitstream(mychannel, "");
                        else
                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
                }
                l = linkbase.next;
-               while (l != &linkbase) {
+               while(l != &linkbase)
+               {
+                       char *s;
+
                        hastx = 1;
                        hastx = 1;
-                       res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
+                       res = saynode(myrpt,mychannel,l->name);
+                       s = "rpt/tranceive";
+                       if (!l->mode) s = "rpt/monitor";
+                       if (!l->thisconnected) s = "rpt/connecting";
+                       res = ast_streamfile(mychannel, s, mychannel->language);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
                        else
                                ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
                        else
                                ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
-                       ast_say_character_str(mychannel, l->name, NULL, mychannel->language);
+                       l = l->next;
+               }                       
+               if (!hastx)
+               {
+                       res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
+                       if (!res) 
+                               res = ast_waitstream(mychannel, "");
+                       else
+                                ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
+                       ast_stopstream(mychannel);
+               }
+               /* destroy our local link queue */
+               l = linkbase.next;
+               while(l != &linkbase)
+               {
+                       l1 = l;
+                       l = l->next;
+                       remque((struct qelem *)l1);
+                       ast_free(l1);
+               }                       
+               imdone = 1;
+               break;
+           case FULLSTATUS:
+               rpt_mutex_lock(&myrpt->lock);
+               /* get all the nodes */
+               __mklinklist(myrpt,NULL,lbuf);
+               rpt_mutex_unlock(&myrpt->lock);
+               /* parse em */
+               ns = finddelim(lbuf,strs,MAXLINKLIST);
+               /* sort em */
+               if (ns) qsort((void *)strs,ns,sizeof(char *),mycompar);
+               /* wait a little bit */
+               wait_interval(myrpt, DLY_TELEM, mychannel);
+               hastx = 0;
+               res = saynode(myrpt,mychannel,myrpt->name);
+               if (myrpt->callmode)
+               {
+                       hastx = 1;
+                       res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
                        else
                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
                        else
                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
-                       res = ast_streamfile(mychannel, ((l->mode) ? 
-                               "rpt/tranceive" : "rpt/monitor"), mychannel->language);
+               }
+               /* go thru all the nodes in list */
+               for(i = 0; i < ns; i++)
+               {
+                       char *s,mode = 'T';
+
+                       /* if a mode spec at first, handle it */
+                       if ((*strs[i] < '0') || (*strs[i] > '9'))
+                       {
+                               mode = *strs[i];
+                               strs[i]++;
+                       }
+
+                       hastx = 1;
+                       res = saynode(myrpt,mychannel,strs[i]);
+                       s = "rpt/tranceive";
+                       if (mode == 'R') s = "rpt/monitor";
+                       if (mode == 'C') s = "rpt/connecting";
+                       res = ast_streamfile(mychannel, s, mychannel->language);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
                        else
                                ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
                        else
                                ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
-                       l = l->next;
                }                       
                }                       
-               if (!hastx) {
+               if (!hastx)
+               {
                        res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
                        res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
                        if (!res) 
                                res = ast_waitstream(mychannel, "");
@@ -2300,139 +4932,210 @@ static void *rpt_tele_thread(void *this)
                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
                }
                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
                        ast_stopstream(mychannel);
                }
-               /* destroy our local link queue */
-               l = linkbase.next;
-               while (l != &linkbase) {
-                       m = l;
-                       l = l->next;
-                       remque((struct qelem *)m);
-                       ast_free(m);
-               }                       
                imdone = 1;
                break;