#include "./include/mgcp_pub.h"
#include "./include/mgcp.h"
#include "./include/mgcp_const.h"
#include "./include/mgcp_ext.h"
#include "./include/mgcp_struct.h"
#include "./include/mgcp_trans.h"
#include "./include/mgcp_msg.h"

extern int mgcp_get_port();
extern void mgcp_port_init(WORD port);
extern int mgcp_log_err(BYTE *errMsg);
extern int  mgcp_asciout_proc(BYTE *outStr);

int mgcp_cmd_str_to_api(char *str, BYTE *cmd)
{
    if (strcasecmp(str, "CRCX") == 0)
        *cmd = MGCP_CMD_CRCX;
    else if (strcasecmp(str, "MDCX") == 0)
        *cmd = MGCP_CMD_MDCX;
    else if (strcasecmp(str, "DLCX") == 0)
        *cmd = MGCP_CMD_DLCX;
    else if (strcasecmp(str, "RQNT") == 0)
        *cmd = MGCP_CMD_RQNT;
    else if (strcasecmp(str, "NTFY") == 0)
        *cmd = MGCP_CMD_NTFY;
    else if (strcasecmp(str, "AUEP") == 0)
        *cmd = MGCP_CMD_AUEP;
    else if (strcasecmp(str, "RSIP") == 0)
        *cmd = MGCP_CMD_RSIP;
    else
    {       
        return -1;
    }
        
    return 0;
}

int mgcp_mgtype_str_to_api(char *str, BYTE *mgtp, BYTE *porttp)
{
    if (strcasecmp(str, "e1") == 0)
    {   
    *mgtp = MGCP_MG_TYPE_AudioCoder;
    *porttp = MGCP_PORT_TYPE_E1;
  }
  else if (strcasecmp(str, "t1") == 0)
  { 
    *mgtp = MGCP_MG_TYPE_AudioCoder;
    *porttp = MGCP_PORT_TYPE_T1;
  }
  else if (strcasecmp(str, "ann") == 0)
  { 
    *mgtp = MGCP_MG_TYPE_ANN;
    *porttp = 0;
  }
  else if (strcasecmp(str, "aaln") == 0)
  { 
    *mgtp = MGCP_MG_TYPE_AudioCoder;
    *porttp = MGCP_PORT_TYPE_AALN;
  }
  else
  {
      if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "Wrong mg type\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
        }
        
        return -1;
  }
        
  return 0;
}

int mgcp_mode_str_to_api(char *str, BYTE *md)
{
    if (strcasecmp(str, "inactive") == 0)
        *md = MGCP_CON_MODE_INACTIVE;
  else if (strcasecmp(str, "recvonly") == 0)
        *md = MGCP_CON_MODE_RECVONLY;
  else if (strcasecmp(str, "sendonly") == 0)
        *md = MGCP_CON_MODE_SENDONLY;
  else if (strcasecmp(str, "sendrecv") == 0)
        *md = MGCP_CON_MODE_SENDRECV;
  else
  {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "Wrong connect mode\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
        }
            
        return -1;
  }
        
  return 0;
}

int mgcp_rm_str_to_api(char *str, BYTE *rm)
{
    if (strcasecmp(str, "restart") == 0)
        *rm = MGCP_RST_MODE_RESTART;
  else if (strcasecmp(str, "forced") == 0)
        *rm = MGCP_RST_MODE_FORCED;
  else if (strcasecmp(str, "disconnected") == 0)
        *rm = MGCP_RST_MODE_DISCONNECTED;
  else if (strcasecmp(str, "graceful") == 0)
        *rm = MGCP_RST_MODE_GRACEFUL;
  else if (strcasecmp(str, "cancel-graceful") == 0)
        *rm = MGCP_RST_MODE_CANCEL_GRACEFUL;        
  else
  {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "Wrong restart mode\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
        }
        
        return -1;
  }
        
  return 0;
}

int mgcp_pkg_str_to_api(char *str, BYTE *pkg)
{
    if (strcasecmp(str, "L") == 0)
        *pkg = MGCP_PKG_L;
    else if (strcasecmp(str, "D") == 0)
        *pkg = MGCP_PKG_D;
    else if (strcasecmp(str, "G") == 0)
        *pkg = MGCP_PKG_G;          
    else
        return -1;
        
  return 0;
}

int mgcp_sig_str_to_api(char *str, BYTE *sig, BYTE pkg)
{
  if (MGCP_PKG_L == pkg)
  {
    if (strcasecmp(str, "aw") == 0)
        *sig = MGCP_L_SIG_AW;   
    else if (strcasecmp(str, "dl") == 0)
        *sig = MGCP_L_SIG_DL;
    else if (strcasecmp(str, "bz") == 0)
        *sig = MGCP_L_SIG_BZ;  
    else if (strcasecmp(str, "wt") == 0)
        *sig = MGCP_L_SIG_WT;
    else if (strcasecmp(str, "nbz") == 0)
        *sig = MGCP_L_SIG_NBZ;
    else if (strcasecmp(str, "rg") == 0)
        *sig = MGCP_L_SIG_RG;
    else if (strcasecmp(str, "e") == 0)
        *sig = MGCP_L_SIG_E;
    else if (strcasecmp(str, "ot") == 0)
        *sig = MGCP_L_SIG_OT;
    else
        return -1;    
  }
  else if (MGCP_PKG_D == pkg)
  {       
    if (strcasecmp(str, "0") == 0)
        *sig = MGCP_D_SIG_ZERO;
    else if (strcasecmp(str, "1") == 0)
        *sig = MGCP_D_SIG_ONE;
    else if (strcasecmp(str, "2") == 0)
        *sig = MGCP_D_SIG_TWO;
    else if (strcasecmp(str, "3") == 0)
        *sig = MGCP_D_SIG_THREE;
    else if (strcasecmp(str, "4") == 0)
        *sig = MGCP_D_SIG_FOUR;
    else if (strcasecmp(str, "5") == 0)
        *sig = MGCP_D_SIG_FIVE;
    else if (strcasecmp(str, "6") == 0)
        *sig = MGCP_D_SIG_SIX;
    else if (strcasecmp(str, "7") == 0)
        *sig = MGCP_D_SIG_SEVEN;
    else if (strcasecmp(str, "8") == 0)
        *sig = MGCP_D_SIG_EIGHT;
    else if (strcasecmp(str, "9") == 0)
        *sig = MGCP_D_SIG_NINE;
    else if (strcasecmp(str, "#") == 0)
        *sig = MGCP_D_SIG_POUND;
    else if (strcasecmp(str, "*") == 0)
        *sig = MGCP_D_SIG_STAR;
    else 
        return -1;    
  }
  else if (MGCP_PKG_G == pkg)
  {     
    if (strcasecmp(str, "rt") == 0)
        *sig = MGCP_G_SIG_RT;
    else if (strcasecmp(str, "cf") == 0)
        *sig = MGCP_G_SIG_CF;
    else if (strcasecmp(str, "cg") == 0)
        *sig = MGCP_G_SIG_CG;
    else if (strcasecmp(str, "it") == 0)
        *sig = MGCP_G_SIG_IT; 
    else if (strcasecmp(str, "pt") == 0)
        *sig = MGCP_G_SIG_PT;
    else
        return -1;   
  }                                                                         
  else
     return -1;     
        
  return 0;
}

int mgcp_event_str_to_api(char *str, BYTE *ent, BYTE pkg)
{
   if (MGCP_PKG_L == pkg)
   {    
    if (strcasecmp(str, "hd") == 0)
        *ent = MGCP_L_EVENT_HD;
    else if (strcasecmp(str, "hu") == 0)
        *ent = MGCP_L_EVENT_HU;  
    else if (strcasecmp(str, "hf") == 0)
        *ent = MGCP_L_EVENT_HF; 
    else if (strcasecmp(str, "aw") == 0)
        *ent = MGCP_L_EVENT_AW;  
    else if (strcasecmp(str, "nbz") == 0)
        *ent = MGCP_L_EVENT_NBZ;
    else if (strcasecmp(str, "e") == 0)
        *ent = MGCP_L_EVENT_E; 
    else if (strcasecmp(str, "oc") == 0)
        *ent = MGCP_L_EVENT_OC;  
    else if (strcasecmp(str, "of") == 0)
        *ent = MGCP_L_EVENT_OF;
    else
        return -1;    
   }
   else if (MGCP_PKG_D == pkg)
   {
    if (strcasecmp(str, "0") == 0)
        *ent = MGCP_D_EVENT_ZERO;  
    else if (strcasecmp(str, "1") == 0)
        *ent = MGCP_D_EVENT_ONE; 
    else if (strcasecmp(str, "2") == 0)
        *ent = MGCP_D_EVENT_TWO;  
    else if (strcasecmp(str, "3") == 0)
        *ent = MGCP_D_EVENT_THREE;
    else if (strcasecmp(str, "4") == 0)
        *ent = MGCP_D_EVENT_FOUR; 
    else if (strcasecmp(str, "5") == 0)
        *ent = MGCP_D_EVENT_FIVE;  
    else if (strcasecmp(str, "6") == 0)
        *ent = MGCP_D_EVENT_SIX;
    else if (strcasecmp(str, "7") == 0)
        *ent = MGCP_D_EVENT_SEVEN; 
    else if (strcasecmp(str, "8") == 0)
        *ent = MGCP_D_EVENT_EIGHT;  
    else if (strcasecmp(str, "9") == 0)
        *ent = MGCP_D_EVENT_NINE;
    else if (strcasecmp(str, "#") == 0)
        *ent = MGCP_D_EVENT_POUND; 
    else if (strcasecmp(str, "*") == 0)
        *ent = MGCP_D_EVENT_STAR;
    else
         return -1;    
   }
   else if (MGCP_PKG_G == pkg)
   {        
    if (strcasecmp(str, "mt") == 0)
        *ent = MGCP_G_EVENT_MT;  
    else if (strcasecmp(str, "ft") == 0)
        *ent = MGCP_G_EVENT_FT;
    else if (strcasecmp(str, "ld") == 0)
        *ent = MGCP_G_EVENT_LD; 
    else if (strcasecmp(str, "of") == 0)
        *ent = MGCP_G_EVENT_OF;
    else
        return -1;   
   }                                                            
   else
        return -1;      
        
  return 0;
}

void mgcp_util_replace_all_lws(char *msg)
{
    char *tmp;

    if (msg == NULL)
        return;
    tmp = msg;
    
    for (; tmp[0] != '\0'; tmp++)
    {
        if (('\0' == tmp[0]) || ('\0' == tmp[1])    ||
            ('\0' == tmp[2]) || ('\0' == tmp[3]))
            return;

        if ((('\r' == tmp[0]) && ('\n' == tmp[1])   &&
             ('\r' == tmp[2]) && ('\n' == tmp[3]))  ||
            (('\r' == tmp[0]) && ('\r' == tmp[1]))  ||
            (('\n' == tmp[0]) && ('\n' == tmp[1])))
            return;

        if ((('\r' == tmp[0]) && ('\n' == tmp[1])   &&
            ((' ' == tmp[2]) || ('\t' == tmp[2])))  ||      
            (('\r' == tmp[0]) && 
            ((' ' == tmp[1]) || ('\t' == tmp[1])))  ||
            (('\n' == tmp[0]) &&
            ((' ' == tmp[1]) || ('\t' == tmp[1]))))
        {
            // Replace line end and TAB symbols by SP
            tmp[0] = ' ';
            tmp[1] = ' ';
            tmp = tmp + 2;
            // Replace all following TAB symbols
            for (; ('\t' == tmp[0] || ' ' == tmp[0]); )
            {
                tmp[0] = ' ';
                tmp++;
            }
        }
    }
}

int mgcp_find_next_crlf(char *startOfHeader, char **endOfHeader)
{
    char *soh = startOfHeader;

    *endOfHeader = NULL;

    while (('\r' != *soh) && ('\n' != *soh))
    {
        if (*soh)
            soh++;
        else
        {
                  printf("Final CRLF is missing\n");
                  
                  if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
              {
                   sprintf(mgcpAsciTempBuf, "Final CRLF is missing\r\n");
                   mgcp_log_err(mgcpAsciTempBuf);
              } 
                    
            return -1;
        }
    }
    
    // case 1: CRLF is the separator
    // case 2 or 3: CR or LF is the separator
    if (('\r' == soh[0]) && ('\n' == soh[1]))
        soh = soh + 1;

    // VERIFY if TMP is the end of header or LWS.
    // LWS are extra SP, HT, CR and LF contained in headers.
    if ((' ' == soh[1]) || ('\t' == soh[1]))
    {
        // incoming message that potentially
        // contains LWS must be processed with
        // mgcp_util_replace_all_lws(char *)
        printf("Message that contains LWS must be processed with sip_util_replace_all_lws(char *tmp) before being parsed.\n");
        
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
           sprintf(mgcpAsciTempBuf, "Message that contains LWS must be processed with sip_util_replace_all_lws(char *tmp) before being parsed.\r\n");
               mgcp_log_err(mgcpAsciTempBuf);
          }         
        
        return -1;
    }

    *endOfHeader = soh + 1;
    
    return 0;
}

char *mgcp_clrncpy(char *dst, char *src, WORD len)
{
    char *pbeg;
    char *pend;
    char *p;
    WORD spaceLessLength;

    if ((src == NULL) || (len == 0))
        return NULL;

    // find the start of relevant text
    pbeg = src;
    while ((' ' == *pbeg) || ('\r' == *pbeg) || ('\n' == *pbeg) || ('\t' == *pbeg))
        pbeg++;

    // find the end of relevant text
    pend = src + len - 1;
    while ((' ' == *pend) || ('\r' == *pend) || ('\n' == *pend) || ('\t' == *pend))
    {
        pend--;
        if (pend < pbeg)
        {
            *dst = '\0';
            return dst;
        }
    }

    // if pend == pbeg there is only one char to copy
    spaceLessLength = pend - pbeg + 1;   // excluding any '\0'
    memcpy(dst, pbeg, spaceLessLength);
    p = dst + spaceLessLength;

    // terminate the string and pad dest with zeros until len
    do
    {
        *p = '\0';
        p++;
        spaceLessLength++;
    }
    while (spaceLessLength < len);

    return dst;
}

int mgcp_msg_start_line_parse_resp(char *buf, char **nextHeader)
{
    char            *hp;
    char            tmp[128];
    char            *statusCode;
    char            *transId;
    char      *endoftransId;
    MGCP_SL         *sl;
    WORD            retCode;
    DWORD           transIdValue;
    int             port;
    
    *nextHeader = buf;

    statusCode = strchr(buf, ' ');       // Search for first SPACE
    if (statusCode == NULL)
        return -1;
    mgcp_clrncpy(tmp, buf, statusCode - buf);
    retCode = strtoul(tmp, NULL, 10);
    
    transId = strchr(statusCode + 1, ' ');
    if (transId == NULL)
        return -1;
  
  mgcp_clrncpy(tmp, statusCode + 1, transId - statusCode - 1);
    transIdValue = strtoul(tmp, &endoftransId, 10);
  if ('\0' != endoftransId[0])
        {
        printf("the space of transId is at wrong position.\n"); 
        return -1;
      }
    
    if ((port = mgcp_match_client_trans(transIdValue)) < 0)
        return -1;
    
    memset(&mgcpRespPara, 0, sizeof(MGCP_PARA));    
        
    sl = &mgcpRespPara.sl;
    sl->cmdRes = MGCP_RESPONSE;
    sl->retCode = retCode;
    sl->transId = transIdValue;
    
    hp = transId;
    while ((*hp != '\r') && (*hp != '\n'))
    {
        if (*hp)
            hp++;
        else
        {
            printf("No crlf found\n");
 
                if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
               sprintf(mgcpAsciTempBuf, "No crlf found\r\n");
                   mgcp_log_err(mgcpAsciTempBuf);
              }   
            
            return -1;
        }
    }
    mgcp_clrncpy(sl->desc, transId + 1, hp - transId - 1);
    
    hp++;
    if ((*hp) && ('\r' == hp[-1]) && ('\n' == hp[0]))
        hp++;
    (*nextHeader) = hp;
    
    return port;
}

int mgcp_msg_start_line_parse_cmd(int *portAllocated, char *buf, char **nextHeader)
{
    char            *hp;
    char            tmp[128];
    char            *cmdName;
    char            *transId;
    char            *mgName;
    char      *endmgName;
    char            *trkNum;
    char            *chlNum;
    char      *endoftransId;
    char      mgtype[128];
    char      *mgtypeslash;
    MGCP_SL         *sl;
    MGCP_PARA       *para;
    MGCP_PORT       *trans;
    int             port;
    BYTE            cmd;
    BYTE      mgtp;
    BYTE      porttp;
    DWORD           transID;
    
    *portAllocated = -1;
    
    *nextHeader = buf;
    
    cmdName = strchr(buf, ' ');       // Search for first SPACE
    if (cmdName == NULL)
        return -1;
    mgcp_clrncpy(tmp, buf, cmdName - buf);
    
    mgcp_cmd_str_to_api(tmp, &cmd);
/*{
        return -1;
    }
*/  
    transId = strchr(cmdName + 1, ' ');
    if (transId == NULL)
        return -1;
    
  mgcp_clrncpy(tmp, cmdName + 1, transId - cmdName - 1);
    transID = strtoul(tmp, &endoftransId, 10);
    if ('\0' != endoftransId[0])
        {
        printf("the space of transId is at wrong position.\n"); 
        
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
    {
       sprintf(mgcpAsciTempBuf, "the space of transId is at wrong position.\r\n");
       mgcp_log_err(mgcpAsciTempBuf);
      }         
        
        return -1;
      }
      
    if ((cmd<MGCP_CMD_CRCX) || (cmd>MGCP_CMD_RSIP))
    {
        printf("unknown or unsupport command\n");
        
          if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
      {
         sprintf(mgcpAsciTempBuf, "unknown or unsupport command\r\n");
         mgcp_log_err(mgcpAsciTempBuf);
        }       
        
      mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNCMD_INDEX);
      return -1;
    }  
    
    if ((port = mgcp_match_server_trans(transID)) >= 0)
    {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
           sprintf(mgcpAsciTempBuf, "Find the same transID\n");
           mgcp_log_err(mgcpAsciTempBuf);
        }           
        return -2;
    }   
    
    if ((port = mgcp_get_port()) < 0)
    {
        return -1;
    }
    *portAllocated = port;
    
    trans = &mgcpPort[port];
    para = &trans->para;
    sl = &para->sl;
    
    hp = transId;
    while ((*hp != '\r') && (*hp != '\n'))
    {
        if (*hp)
            hp++;
        else
        {
            printf("No crlf found\n");
            return -1;
        }
    }
    mgcp_clrncpy(tmp, transId + 1, hp - transId - 1);
    
    if ((mgName = strchr(tmp, '@')) == NULL)
    {
        
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
        }       
        
        mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX); 
        return -1;
    }
    
    if ((endmgName = strstr(mgName, " ")) == NULL)
    {
        
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
        }       
        
        mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX); 
          return -1;
    }
    
    if (NULL == mgcp_clrncpy(sl->mgName, mgName+1, endmgName-mgName-1))
    {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "endpoint unknown:no domain name\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
        }       
        
        mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX); 
          return -1;        
    }
    
    if (isdigit(tmp[0])||(tmp[0]=='*'))
    {
        sl->epNameMethod = MGCP_EP_NAME_UNSTRUCTURED;
        if (tmp[0] == '*')
            sl->chlNum = MGCP_EP_NAME_CHNL_WILDCAST;
        else
            sl->chlNum = strtoul(tmp, NULL, 10);
    }
    else
    {
        sl->epNameMethod = MGCP_EP_NAME_STRUCTURED;
        if (((trkNum = strchr(tmp, '-')) != NULL) 
            && (trkNum < mgName))
        {
            if (((mgtypeslash = strchr(tmp, '/')) == NULL) || (mgtypeslash >= trkNum))
            {
                if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
                {
                    sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
                    mgcp_log_err(mgcpAsciTempBuf);
                }               
                
                mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX); 
                return -1;
            } 
            
            mgcp_clrncpy(mgtype, mgtypeslash +1, trkNum - mgtypeslash - 1);
            
            if (mgcp_mgtype_str_to_api(mgtype, &mgtp, &porttp) < 0)
            {
                if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
                {
                    sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
                    mgcp_log_err(mgcpAsciTempBuf);
                }                 
                
                mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX);   
              return -1;
            }   
            
            if ('*' == trkNum[1])
            {
              sl->trkNum = MGCP_EP_NAME_TRK_WILDCAST;               
            }   
            else
            {       
              sl->trkNum = strtoul(trkNum + 1, NULL, 10);
            }
            
            if ((chlNum = strchr(trkNum + 1, '/')) != NULL)
            {
                if (chlNum[1] == '*')
                    sl->chlNum = MGCP_EP_NAME_CHNL_WILDCAST;
                else
                    sl->chlNum = strtoul(chlNum + 1, NULL, 10);
            }
            else
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
              {
                sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
                mgcp_log_err(mgcpAsciTempBuf);
              }             
                
              mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX);
              return -1;
            }
        }
        else if(((NULL == trkNum) && ('a' == tmp[0])) 
                 || ((trkNum != NULL) && (trkNum >= mgName)))
        {
            if ((chlNum = strchr(tmp, '/')) != NULL)
            {
                mgcp_clrncpy(mgtype, tmp, chlNum - tmp);
                
                if (mgcp_mgtype_str_to_api(mgtype, &mgtp, &porttp) < 0)
                {
                  if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
                  {
                    sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
                    mgcp_log_err(mgcpAsciTempBuf);
                  }                 
                    
                    mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX); 
                    return -1;
                }
                    
                if (MGCP_PORT_TYPE_AALN == porttp)
                {   
                  if (chlNum[1] == '*')
                      sl->trkNum = MGCP_EP_NAME_TRK_WILDCAST;
                  else
                      sl->trkNum = strtoul(chlNum + 1, NULL, 10);
                      
                  sl->chlNum = 0;  
                }
                else
                {
                  if (chlNum[1] == '*')
                      sl->chlNum = MGCP_EP_NAME_CHNL_WILDCAST;
                  else
                      sl->chlNum = strtoul(chlNum + 1, NULL, 10);
                      
                  sl->trkNum = MGCP_EP_NAME_TRK_WILDCAST;
                }               
            }
            else
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
              {
                sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
                mgcp_log_err(mgcpAsciTempBuf);
              }             
                
                mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX);
                return -1;
            }
        }
        else
        {
          if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
          {
            sprintf(mgcpAsciTempBuf, "endpoint unknown\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
          }             
            
          mgcp_send_incmd_rsp(transID, MGCP_RET_CODE_UNEP_INDEX);   
          return -1;
        }
    }
    
    trans->transId = transID;
    trans->cmd = cmd;
    
    para->ip = mgcpRvMsg.msgSrcIP;
    para->peerPort = mgcpRvMsg.msgSrcPort;
    para->localPort = mgcpRvMsg.msgDstPort;
    
//  mgcp_clrncpy(sl->mgName, mgName+1, endmgName-mgName-1);
    sl->cmdRes = MGCP_COMMAND;
    sl->transId = transID;
    sl->mgType = mgtp;
    sl->portType = porttp;
    
    hp++;
    if ((*hp) && ('\r' == hp[-1]) && ('\n' == hp[0]))
        hp++;  
        (*nextHeader) = hp;
 
        return port;    
}

int mgcp_msg_start_line_parse(BYTE *cmdRes, char *buf, char **nextHeader)
{
    int port = -1;
    int ret;
    
    if (isdigit(buf[0]))
    {
        if ((port = mgcp_msg_start_line_parse_resp(buf, nextHeader)) < 0)
            return -1;
        *cmdRes = MGCP_RESPONSE;
    }
    else
    {
        if ((ret = mgcp_msg_start_line_parse_cmd(&port, buf, nextHeader)) < 0)
        {
            if (port >= 0)
                mgcp_port_init(port);
            
            if (ret == -2)
                return -2;
            else        
                return -1;
        }
        mgcpPort[port].reqInd = MGCP_INDICATION;
        *cmdRes = MGCP_COMMAND;
    }
    
    return port;
}

int mgcp_con_id_parse(MGCP_I *conId, char *value)
{
    if (NULL == value)
        return -1;
                
    strcpy(conId->conId, value);
    return 0;
}

int mgcp_call_id_parse(MGCP_C *callId, char *value)
{
    if (NULL == value)
        return -1;
    
    strcpy(callId->callId, value);
      return 0; 
}

int mgcp_local_opt_p_parse(MGCP_L *localopt, char *value)
{
    if (NULL == value)
        return -1;
        
    localopt->p=atoi(value);
      return 0; 
}

int mgcp_local_opt_a_parse(MGCP_L *localopt, char *value)
{
    if (NULL == value)
        return -1;
    
    strcpy(localopt->codec, value);
      return 0;
}

int mgcp_local_opt_nt_parse(MGCP_L *localopt, char *value)
{
    if (NULL == value)
        return -1;
    if (0 == strcasecmp(value, "IN"))
        {
            localopt->ecDisable=0;
            localopt->ssDisable=0;
            return 0;
        }
    else if (0 == strcasecmp(value, "IN, e:off"))
        {
            localopt->ecDisable=1;
            localopt->ssDisable=0;
            return 0;
        }
    else if (0 == strcasecmp(value, "IN, s:off"))
        {
            localopt->ecDisable=0;
            localopt->ssDisable=1;          
            return 0;
        }
    else if (0 == strcasecmp(value, "IN, e:off, s:off"))
        {
            localopt->ecDisable=1;
            localopt->ssDisable=1;          
            return 0;
        }
    else
        return -1;  
}

int mgcp_local_opt_es_cci_parse(MGCP_L *localopt, char *value)
{
    if (NULL == value)
        return -1;

    strcpy(localopt->esCci, value);

    localopt->flag |= MGCP_PARA_L_FLAG_ESS_CCI;

    return 0;
}

int mgcp_local_opt_es_ccd_parse(MGCP_L *localopt, char *value)
{
    char    *colon;
    int	len;

    if (NULL == value)
        return -1;

    if (((colon = strchr(value, ':')) == NULL) || (value > colon))
    {
        sprintf(mgcpAsciTempBuf, "es ccd wrong format\r\n");
        mgcp_log_err(mgcpAsciTempBuf);
        return -1;
    }

   if ((len = (colon - value)) > MGCP_MAX_DOMAIN_LEN)
   {
       sprintf(mgcpAsciTempBuf, "es ccd domain to long\r\n");
       mgcp_log_err(mgcpAsciTempBuf);
       return -1;
   }

   mgcp_clrncpy(localopt->esCcd.domain, value, len);

   localopt->esCcd.port = strtol(colon+1, NULL, 10);

   localopt->flag |= MGCP_PARA_L_FLAG_ESS_CCD;

   return 0;
    
}

int mgcp_local_opt_parse(MGCP_L *localopt, char *value)
{
    char hvaluename[64];
    char hvalue[128];
    char *colonIndex;
    char *comma;
    char *endofvalue = value;
    char *begofvalue = value;
    int len, commaNum = 0;
    
    if (NULL == value)
        return -1;      
    
  for (;;)
    {
    if ('\0' == *begofvalue)
        return 0;   
        
    begofvalue = endofvalue;
    
/*    if (2 > commaNum)
    {
      while(',' != *endofvalue)
        {
                if (*endofvalue)
                    endofvalue++;
                else
                {
                    printf("lack of comma,can not find endofvalue\n");
                  return -1;
                }       
        }
    commaNum++;     
    }*/
    if ((comma =strchr(endofvalue, ',')) != NULL)
    {
        endofvalue = comma;
        commaNum++;
    }
    else
    {
        if (commaNum < 2)
        {
            mgcp_log_err("mgcp l parse:lack of comma,can not find endofvalue\r\n");
            return -1;
        }

      while('\0' != *endofvalue)
        {
                if (*endofvalue)
                    endofvalue++;       
        }
    }   
    colonIndex = strchr (begofvalue, ':');
    
    if (NULL == colonIndex)
        {
            printf("can not find colonIndex in the value of Lopt, the wrong format.\n");
            return -1;
        }
        
    if (endofvalue < colonIndex)
        return -1;
            
        len = colonIndex - begofvalue;
        mgcp_clrncpy(hvaluename, begofvalue, len);
        
        len = endofvalue -colonIndex-1;
      mgcp_clrncpy(hvalue, colonIndex+1, len);
      
      if (strncasecmp(hvaluename, "p", 1) == 0)
        {
            if (mgcp_local_opt_p_parse(localopt, hvalue) < 0)
            return -1;
        }
      else if (strncasecmp(hvaluename, "a", 1) == 0)
        {
            if (mgcp_local_opt_a_parse(localopt, hvalue) < 0)
            return -1;
        }
      else if (strncasecmp(hvaluename, "nt", 2) == 0)
        {
          if (mgcp_local_opt_nt_parse(localopt, hvalue) < 0)
          return -1;
        }
    else if (strncasecmp(hvaluename, "es-cci", 6) == 0)
    {
        if (mgcp_local_opt_es_cci_parse(localopt, hvalue) < 0)
            return -1;
    }
    else if (strncasecmp(hvaluename, "es-ccd", 6) == 0)
    {
        if (mgcp_local_opt_es_ccd_parse(localopt, hvalue) < 0)
            return -1;
    }
      else
        return -1;      
 
  begofvalue = endofvalue++;
  }
  
}

int mgcp_connect_mode_parse(MGCP_M *m, char *value)
{
    if (NULL == value)
        return -1;
    
    if (mgcp_mode_str_to_api(value, &m->mode) < 0)
        return -1;
    
    return 0;   
}

int mgcp_observed_reqId_parse(MGCP_O *o, char *value)
{
    if (NULL == value)
        return -1;
        
    strcpy(o->reqId, value);
      return 0; 
}

int mgcp_event_parse(DWORD transId, MGCP_O *o, char *value)
{       
    char hvalue[128];   
    char *begofvalue =value;
    char *endofvalue;
    char *slashIndex;
    int len;
    
    if (NULL == value)
        return -1;  
    
    while('\0' != *begofvalue)
    {
        if(*begofvalue)
            begofvalue++;
    }   
    endofvalue = begofvalue;
    
    slashIndex = strchr(value, '/');
    if(NULL == slashIndex)
        {
            printf("can not find slash in event, the wrong format.\n");
            return -1;
        }
    
    len=slashIndex-value;       
    mgcp_clrncpy(hvalue, value, len);

    if (mgcp_pkg_str_to_api(hvalue, &o->package) < 0)
        {
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
      {
        sprintf(mgcpAsciTempBuf, "unsupported or unknown package\r\n");
        mgcp_log_err(mgcpAsciTempBuf);
      }             
            
            mgcp_send_incmd_rsp(transId, MGCP_RET_CODE_UNPKG_INDEX);
            printf("event package is unknown\n");
            return -1;
        }
    
    len=endofvalue-slashIndex-1;
    mgcp_clrncpy(hvalue, slashIndex+1, len);

  if (mgcp_event_str_to_api(hvalue, &o->event, o->package) < 0) 
  {
    if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
    {
      sprintf(mgcpAsciTempBuf, "no such event\r\n");
      mgcp_log_err(mgcpAsciTempBuf);
    }           
            
    mgcp_send_incmd_rsp(transId, MGCP_RET_CODE_NES_INDEX); 
    printf("event is unknown\n");
    return -1;
  }
        
  return 0; 
}

int mgcp_signl_reqId_parse(MGCP_S *s, char *value)
{
    if (NULL == value)
        return -1;
        
    strcpy(s->reqId, value);
      return 0; 
}

int mgcp_signl_parse(DWORD transId, MGCP_S *s, char *value)
{   
    char hvalue[128];   
    char *begofvalue =value;
    char *endofvalue;
    char *slashIndex;
    int len;
    
    if (NULL == value)
        return -1;  
    
    if (0 == strcmp(value, ""))
    {
        s->signal = MGCP_PACKAGE_SIG_NONE;
        return 0;
    }
    
    while('\0' != *begofvalue)
    {
        if(*begofvalue)
            begofvalue++;
    }   
    endofvalue = begofvalue;
    
    slashIndex = strchr(value, '/');
    if(NULL == slashIndex)
        {
            printf("can not find slash in signal event, the wrong format.\n");
            return -1;
        }
    
    len=slashIndex-value;       
    mgcp_clrncpy(hvalue, value, len);

    if (mgcp_pkg_str_to_api(hvalue, &s->pkg) < 0)
    {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "unsupported or unknown package\r\n");
            mgcp_log_err(mgcpAsciTempBuf);
        }           
            
        mgcp_send_incmd_rsp(transId, MGCP_RET_CODE_UNPKG_INDEX);
        printf("signal package is unknown\n");
        return -1;
    }
    
    len=endofvalue-slashIndex-1;
    mgcp_clrncpy(hvalue, slashIndex+1, len);

    if (mgcp_sig_str_to_api(hvalue, &s->signal, s->pkg) < 0)    
    {
      if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
      {
        sprintf(mgcpAsciTempBuf, "no such signal\r\n");
        mgcp_log_err(mgcpAsciTempBuf);
      }         
            
      mgcp_send_incmd_rsp(transId, MGCP_RET_CODE_NES_INDEX);
      printf("signal event is unknown\n");
      return -1;
    }
        
    return 0;       
}


int mgcp_reqent_parse(DWORD transId, MGCP_R *r, char *value)
{
    char hvalue[128];   
    char *begofvalue =value;
    char *endofvalue;
    char *slashIndex;
    int len;
    
    if (NULL == value)
        return -1;  
    
    while('\0' != *begofvalue)
    {
        if(*begofvalue)
            begofvalue++;
    }   
    endofvalue = begofvalue;
    
    slashIndex = strchr(value, '/');
    if(NULL == slashIndex)
        {
            printf("can not find slash in signal event, the wrong format.\n");
            return -1;
        }
    
    len=slashIndex-value;       
    mgcp_clrncpy(hvalue, value, len);

    if (mgcp_pkg_str_to_api(hvalue, &r->pkg) < 0)
    {
      if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
      {
        sprintf(mgcpAsciTempBuf, "unsupported or unknown package\r\n");
        mgcp_log_err(mgcpAsciTempBuf);
      }             
            
      mgcp_send_incmd_rsp(transId, MGCP_RET_CODE_UNPKG_INDEX);
      printf("request event package is unknown\n");
      return -1;
    }
    
    len=endofvalue-slashIndex-1;
    mgcp_clrncpy(hvalue, slashIndex+1, len);

    if (mgcp_event_str_to_api(hvalue, &r->event, r->pkg) < 0)   
    {
      if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
      {
        sprintf(mgcpAsciTempBuf, "no such request event\r\n");
        mgcp_log_err(mgcpAsciTempBuf);
      }         
            
      mgcp_send_incmd_rsp(transId, MGCP_RET_CODE_NES_INDEX);
      printf("request event is unknown\n");
      return -1;
    }
        
    return 0;
}

int mgcp_restart_mode_parse(MGCP_RM *rm, char *value)
{
    if (NULL == value)
        return -1;
        
    if (mgcp_rm_str_to_api(value, &rm->rm) < 0)
    {
        return -1;
    }
        
      return 0; 
}

int mgcp_restart_delay_parse(MGCP_RD *rd, char *value)
{
    if (NULL == value)
        return -1;
        
    rd->rd = atoi(value);
    return 0;       
}

int mgcp_msg_params_parse(BYTE cmdRes, WORD port, char *buf, char **body)
{
    char        *colonIndex;
    char        hname[64];
    char        hvalue[128];
    char        *startOfHeader = buf;
    char        *endOfHeader;
    char        *end;
    BYTE        S_R_Flag = 0;
    BYTE        len;
    MGCP_PARA   *para;
    
    if (cmdRes == MGCP_COMMAND)
    {   
        para = &mgcpPort[port].para;
    }
    else if (cmdRes == MGCP_RESPONSE)
    {
        para = &mgcpRespPara;
    }   
    else
        return -1;
        
    if ((startOfHeader[0] == '\0') && (mgcpPort[port].cmd != MGCP_CMD_AUEP)&&(cmdRes == MGCP_COMMAND))
    {
        printf("no parameter in buf.\n");
        return -1;
    }       
    
    for (;;)
    {
        if (startOfHeader[0] == '\0')
        {
            *body = NULL;
            return 0;
        }
        
        if (mgcp_find_next_crlf(startOfHeader, &endOfHeader) < 0)
        {
            printf("End of header Not found\n");
            return -1;
        }
        
        if ((startOfHeader[0] == '\r') || (startOfHeader[0] == '\n'))
        {
            *body = startOfHeader;
            return 0;
        }
        else if (((startOfHeader[0] == '.') && (startOfHeader[1] == '\r') && (startOfHeader[2] == '\n')))
        {
            *body = startOfHeader + 3;
            return 1;
        }
            
        // find the header name
        colonIndex = strchr(startOfHeader, ':');
        if (colonIndex == NULL)
        {
            printf("End of header Not found\n");
            return -1;
        }
        if (endOfHeader <= colonIndex)
        {
            printf("Malformed message\n");
            return -1;
        }
        len = colonIndex - startOfHeader;
        mgcp_clrncpy(hname, startOfHeader, len);
        
        // END of header is (end_of_header-2) if header separation is CRLF
        // END of header is (end_of_header-1) if header separation is CR or LF
        if ((endOfHeader[-2] == '\r') || (endOfHeader[-2] == '\n'))
            end = endOfHeader - 2;
        else
            end = endOfHeader - 1;
        if ((end - colonIndex) < 2)
            strcpy(hvalue, "");        // some headers can be empty
        else
        {
            len = end - colonIndex - 1;
            mgcp_clrncpy(hvalue, colonIndex + 1, len);
        }
        
        if (strncasecmp(hname, "I", 1) == 0)
        {
            if (mgcp_con_id_parse(&para->i, hvalue) < 0)
            {
                  if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
              sprintf(mgcpAsciTempBuf, "incorrect connect id\r\n");
              mgcp_log_err(mgcpAsciTempBuf);
            }               
                
                mgcp_send_incmd_rsp(mgcpPort[port].transId, MGCP_RET_CODE_INCONID_INDEX);   
                return -1;
            }
            para->flag |= MGCP_PARA_FLAG_I;
        }
        
        if (strncasecmp(hname,"C",1) == 0)
        {
          if (mgcp_call_id_parse(&para->c, hvalue) < 0)
          {
                  if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
              sprintf(mgcpAsciTempBuf, "unknown call id\r\n");
              mgcp_log_err(mgcpAsciTempBuf);
            }               
            
            mgcp_send_incmd_rsp(mgcpPort[port].transId, MGCP_RET_CODE_UNCLLID_INDEX);   
            return -1;
          }
          para->flag |= MGCP_PARA_FLAG_C;   
        }
        
        if (strncasecmp(hname,"L",1) == 0)
        {
          if (mgcp_local_opt_parse(&para->l, hvalue) < 0)
          {
                  if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
              sprintf(mgcpAsciTempBuf, "internal inconsistency in LocalConnectionOption\r\n");
              mgcp_log_err(mgcpAsciTempBuf);
            }           
            
            mgcp_send_incmd_rsp(mgcpPort[port].transId, MGCP_RET_CODE_ILCO_INDEX);  
            return -1;
          }
          para->flag |= MGCP_PARA_FLAG_L; 
        }
        
        if (strncasecmp(hname,"M",1) == 0)
        {
          if (mgcp_connect_mode_parse(&para->m, hvalue) < 0)
          {
             mgcp_send_incmd_rsp(mgcpPort[port].transId, MGCP_RET_CODE_UNMD_INDEX); 
             return -1;
          }
          para->flag |=MGCP_PARA_FLAG_M;
        }
        
        if (strncasecmp(hname,"O",1) == 0)
        {
          if ((para->flag & MGCP_PARA_FLAG_O) == 0)
             return -1;         
          if (mgcp_event_parse(mgcpPort[port].transId, &para->o, hvalue) < 0)
             return -1;                  
        }
        
        if (strncasecmp(hname,"X",1) == 0)
        {
          if (mgcpPort[port].cmd == MGCP_CMD_NTFY)
          {         
             if (mgcp_observed_reqId_parse(&para->o, hvalue) < 0)
                return -1;
                para->flag |=MGCP_PARA_FLAG_O;
          }
          else
          {
             if (mgcp_signl_reqId_parse(&para->s, hvalue) < 0)
                return -1;
             S_R_Flag = 1;                            
          }  
        }
        
        if (strncasecmp(hname,"S",1) == 0)
        {
          if (0 == S_R_Flag)            
          {
              printf("Have no requestId.\n");
              return -1;
          }
          if (mgcp_signl_parse(mgcpPort[port].transId, &para->s, hvalue) < 0)
             return -1;
             
          para->flag |=MGCP_PARA_FLAG_S;                             
        }

        if (strncasecmp(hname,"R",2) == 0)
        {
          if(0 == S_R_Flag)
          {
              printf("Have no requestId.\n");
              return -1;
          }
          if (mgcp_reqent_parse(mgcpPort[port].transId, &para->r, hvalue) < 0)
             return -1;
             
          para->flag |=MGCP_PARA_FLAG_R;                     
        }       
        
        if (strncasecmp(hname,"RM",2) == 0)
        {
          if (mgcp_restart_mode_parse(&para->rm, hvalue) < 0)
          {
             mgcp_send_incmd_rsp(mgcpPort[port].transId, MGCP_RET_CODE_UNRM_INDEX);
             return -1;
          }
          para->flag |= MGCP_PARA_FLAG_RM;
        }
        
        if (strncasecmp(hname,"RD",2) == 0)
        {
          if (mgcp_restart_delay_parse(&para->rd, hvalue) < 0)
             return -1;
          para->flag |= MGCP_PARA_FLAG_RD;
        }
        
        
        // continue on the next header
        startOfHeader = endOfHeader;
    }
    
//  return -1;
}

int mgcp_msg_parse_single(char *msg, WORD len, char **nextMsg, WORD networkPort)
{
    char        *nextHeader;
    int         port;
    MGCP_PARA   *para;
    BYTE        cmdRes;
    int         ret;
    
    if ((port = mgcp_msg_start_line_parse(&cmdRes, msg, &nextHeader)) < 0)
    {
        if (port == -1)
        {   
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
                sprintf(mgcpAsciTempBuf, "start_line_parse fault\n%s\n", msg);
                mgcp_log_err(mgcpAsciTempBuf);
            }
        }
        else
        {
            if ((mgcpMonitorFg & MONITOR_ALL) == MONITOR_ALL)
            {
                sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", msg);
                mgcp_asciout_proc(mgcpAsciTempBuf);             
            }           
        }
            
        return -1;
    }
    if (port >= MGCP_MAX_NUM_OF_PORT)
    {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, msg);
            mgcp_log_err(mgcpAsciTempBuf);
        }           
        return -1;
    }
    
    if (cmdRes == MGCP_COMMAND)
    {    
        para = &mgcpPort[port].para;
    }
    else if (cmdRes == MGCP_RESPONSE)
    {
        para = &mgcpRespPara;
    }
    else
    {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, msg);
            mgcp_log_err(mgcpAsciTempBuf);
        }           
        return -1;
    }   
//  else
//      para = &mgcpPort[port].para;
    para->flag |= MGCP_PARA_FLAG_SL;
    
    if ((ret = mgcp_msg_params_parse(cmdRes, port, nextHeader, &nextHeader)) < 0)
    {
        if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
            sprintf(mgcpAsciTempBuf, "params_parse fault\n%s\n", msg);
            mgcp_log_err(mgcpAsciTempBuf);
        }
        
        if (cmdRes == MGCP_COMMAND)     
            mgcp_port_init(port);
            
        return -1;
    }
        
    if (0 == ret)
    {
        if ((MGCP_CMD_CRCX == mgcpPort[port].cmd) || (MGCP_CMD_MDCX == mgcpPort[port].cmd))
        {
            if (nextHeader != NULL)
            {
                pub_sdp_msg_init(&para->sdp);
                if ((ret = pub_sdp_parse(&para->sdp, nextHeader, &nextHeader, 0xFFFFFFFF)) < 0)
                {
                    if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
                    {
                        sprintf(mgcpAsciTempBuf, "remotoconnectiondescriptor error\r\n%s\n", msg);
                        mgcp_log_err(mgcpAsciTempBuf);
                    }           
                    
                    mgcp_send_incmd_rsp(mgcpPort[port].transId, MGCP_RET_CODE_RCD_ERR_INDEX);
                    
                    if (cmdRes == MGCP_COMMAND)
                        mgcp_port_init(port);
                    
                    return -1;
                }
                para->flag |= MGCP_PARA_FLAG_SDP;
            }
        }
    }

    if (cmdRes == MGCP_RESPONSE)
        memcpy(&mgcpPort[port].para, &mgcpRespPara, sizeof(MGCP_PARA));

    if ((mgcpPort[port].para.localPort = networkPort) == MGCP_INT_PORT_2427)
    {
        mgcpPort[port].para.peerPort = MGCP_INT_PORT_2727;
    }
    else
    {
        mgcpPort[port].para.peerPort = MGCP_INT_PORT_2427;
    }

  if (((mgcpMonitorFg & MONITOR_ALL) == MONITOR_ALL) || ((mgcpMonitorFg | MONITOR_ERROR) == MONITOR_ALL))
  {
    if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
    {      
      sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
      mgcp_asciout_proc(mgcpAsciTempBuf);
    }
    else
    {
      sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
      mgcp_asciout_proc(mgcpAsciTempBuf);      
    }
  }
  else if ((mgcpMonitorFg | MONITOR_MG0_MSG | MONITOR_MG1_MSG | MONITOR_MG2_MSG |MONITOR_ERROR) == MONITOR_ALL)
  {
    if ((mgcpMonitorFg & MONITOR_MG0_MSG) == 0)
    {
      if ((mgcpMonitorFg & MONITOR_MG1_MSG) == 0)
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2])))
           {
             if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
             {
               sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
             }
             else
             {
               sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);      
             }
           }
        }
        else
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])))
           {
             if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
             {      
               sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
             }
             else
             {
               sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);      
             }
           }        
        }
      }
      else
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0]))  
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2])))
           {
             if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
             {
               sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
             }
             else
             {
               sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);      
             }
           }
        }
        else
        {
           if (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0]))
           {
             if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
             {   
               sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
             }
             else
             {
               sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);      
             }
           }        
        }      
      }
    }
    else
    {
      if ((mgcpMonitorFg & MONITOR_MG1_MSG) == 0)
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2])))
           {
             if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
             {
               sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
             }
             else
             {
               sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);      
             }
           }
        }
        else
        {
           if (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1]))
           {
             if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
             {
               sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
             }
             else
             {
               sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);      
             }
           }        
        }
      }
      else
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2]))
           {
             if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
             {
               sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
             }
             else
             {
               sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);      
             }
           }
        }      
      }    
    }
  }
  else if (((mgcpMonitorFg & MONITOR_MG0_MSG) == MONITOR_MG0_MSG) 
            || ((mgcpMonitorFg & MONITOR_MG1_MSG) == MONITOR_MG1_MSG) 
            || ((mgcpMonitorFg & MONITOR_MG2_MSG) == MONITOR_MG2_MSG))
  {
    if ((((mgcpMonitorFg & MONITOR_MG0_MSG) == MONITOR_MG0_MSG) && (0 == strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0])))
         || (((mgcpMonitorFg & MONITOR_MG1_MSG) == MONITOR_MG1_MSG) && (0 == strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])))
         || (((mgcpMonitorFg & MONITOR_MG2_MSG) == MONITOR_MG2_MSG) && (0 == strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2]))))
     {
       if (mgcpPort[port].para.sl.cmdRes == MGCP_COMMAND)
       {     
         sprintf(mgcpAsciTempBuf, "Receive Command: %s\r\n", mgcpRvMsg.msgContent);
      
         mgcp_asciout_proc(mgcpAsciTempBuf);
       }
       else
       {
         sprintf(mgcpAsciTempBuf, "Receive Response: %s\r\n", mgcpRvMsg.msgContent);
      
         mgcp_asciout_proc(mgcpAsciTempBuf);      
       }
     }   
  }    
    
   if (1 == ret)
   {
       *nextMsg = nextHeader;
       return 1;
   }
   
    return 0;
}

int mgcp_msg_parse(WORD networkPort)
{
    char        *msg, *nextMsg;
    WORD        len;
    WORD        lenTotal;
    int         ret;
    int         i;

    nextMsg = msg = mgcpRvMsg.msgContent;
    lenTotal = len = mgcpRvMsg.msgLength;
    
    mgcp_util_replace_all_lws(msg);
    
    for (i = 0; i < 10; i++)
    {
        if ((ret = mgcp_msg_parse_single(nextMsg, len, &nextMsg, networkPort)) <= 0)
            break;
        else 
        {
            len = nextMsg - msg;
            
            if (len >= lenTotal)
                break;
            else
                len = lenTotal -len;
        }   
    }
    
    return 1;   
}

void mgcp_recv_msg()
{
    BYTE    i;
    WORD    port;
    
    for (i = 0; i < 64; i++)
    {
        if (i & 1)
            port = MGCP_INT_PORT_2427;
        else
            port = MGCP_INT_PORT_2727;
            
        if (iptrDirectRecvMsg(&mgcpRvMsg, port) > 0)
        {
            if (mgcpRvMsg.msgLength >= 1500)
                continue;
            mgcpRvMsg.msgContent[mgcpRvMsg.msgLength] = '\0';
            mgcp_msg_parse(port);
        }
    }
}

// MGCP Message Encoding

int mgcp_create_req_id(WORD port, char *reqId)
{
    if (port >= MGCP_MAX_NUM_OF_PORT)
        return -1;
    
    if (reqId[0] == '\0')
        sprintf(reqId, "%X%lX", port, time(NULL));
    else
        return 0;   
    
    return 0;
}

int mgcp_ep_id_encode(MGCP_SL *sl, char *endPointId)
{
    char    epType[8];
    
    if (sl->epNameMethod == MGCP_EP_NAME_UNSTRUCTURED)
    {
        if (sl->chlNum == MGCP_EP_NAME_CHNL_WILDCAST)
            sprintf(endPointId, "*");
        else
            sprintf(endPointId, "%d", sl->chlNum);
    }
    else if (sl->epNameMethod == MGCP_EP_NAME_STRUCTURED)
    {
      if ((sl->mgType >= MGCP_MG_TYPE_AudioCoder) && (sl->mgType < MGCP_MG_TYPE_ANN))
        {   
          if ((sl->portType == MGCP_PORT_TYPE_E1) ||
              (sl->portType == MGCP_PORT_TYPE_T1))
          {
              if (sl->portType == MGCP_PORT_TYPE_E1)
                sprintf(epType, "e1");
              else 
                sprintf(epType, "t1");
              if (MGCP_EP_NAME_TRK_WILDCAST == sl->trkNum)
              {     
                if (sl->chlNum == MGCP_EP_NAME_CHNL_WILDCAST)
                  sprintf(endPointId, "ds/%s-*/*", epType);
                else
                  sprintf(endPointId, "ds/%s-*/%d", epType, sl->chlNum);
              }
              else
              {
                if (sl->chlNum == MGCP_EP_NAME_CHNL_WILDCAST)
                  sprintf(endPointId, "ds/%s-%d/*", epType, sl->trkNum);
                else
                  sprintf(endPointId, "ds/%s-%d/%d", epType, sl->trkNum, sl->chlNum);               
              }     
          }
          else if (MGCP_PORT_TYPE_AALN == sl->portType)
          {
              sprintf(epType, "aaln");  
              if (sl->trkNum == MGCP_EP_NAME_TRK_WILDCAST)
                sprintf(endPointId, "%s/*", epType);
              else
                sprintf(endPointId, "%s/%d", epType, sl->trkNum);
          }
          else
              return -1;
      }
        else if (sl->mgType == MGCP_MG_TYPE_ANN)
        {
            sprintf(epType, "ann"); 
            if (sl->chlNum == MGCP_EP_NAME_CHNL_WILDCAST)
                sprintf(endPointId, "%s/*", epType);
            else
                sprintf(endPointId, "%s/%d", epType, sl->chlNum);
        }
        else
            return -1;
    }
    else
        return -1;
    
    return 0;
}

int mgcp_para_call_id_encode(MGCP_C *c, char *msgPara)
{
    if ((c == NULL) ||
        (msgPara == NULL))
        return -1;
    
    sprintf(msgPara, "C: %s\r\n", c->callId);
    
    return 0;
}

int mgcp_para_con_id_encode(MGCP_I *i, char *msgPara)
{
    if ((i == NULL) ||
        (msgPara == NULL))
        return -1;
    
    sprintf(msgPara, "I: %s\r\n", i->conId);
    
    return 0;
}

int mgcp_para_local_con_opt_encode(MGCP_L *l, char *msgPara, WORD flag)
{
    char    codec[16]="";
        
    if ((l == NULL) ||
        (msgPara == NULL))
        return -1;
    
    if ((flag & MGCP_PARA_FLAG_TFO) == MGCP_PARA_FLAG_TFO)
    {
        strcpy(codec, "PCMA");
		if ((l->flag & MGCP_PARA_L_FLAG_ESS_CCI) == MGCP_PARA_L_FLAG_ESS_CCI)
		{
            if ((l->flag & MGCP_PARA_L_FLAG_ESS_CCD) == MGCP_PARA_L_FLAG_ESS_CCD)
            {
                sprintf(msgPara, "L: p:%d, a:%s, nt:IN%s%s, es-cci:%s, es-ccd:%s:%d\r\n", l->p, codec
			            , (l->ecDisable)? ", e:off" : "", (l->ssDisable)? ", s:off" : "", l->esCci, l->esCcd.domain, l->esCcd.port);
            }
			else
			{
                sprintf(msgPara, "L: p:%d, a:%s, nt:IN%s%s, es-cci:%s\r\n", l->p, codec
			            , (l->ecDisable)? ", e:off" : "", (l->ssDisable)? ", s:off" : "", l->esCci);
			}
    }
    else
    {
            sprintf(msgPara, "L: p:%d, a:%s, nt:IN%s%s\r\n", l->p, codec
			        , (l->ecDisable)? ", e:off" : "", (l->ssDisable)? ", s:off" : "");
		}
    }
    else
    {
		if ((l->flag & MGCP_PARA_L_FLAG_ESS_CCI) == MGCP_PARA_L_FLAG_ESS_CCI)
		{
            if ((l->flag & MGCP_PARA_L_FLAG_ESS_CCD) == MGCP_PARA_L_FLAG_ESS_CCD)
            {
                sprintf(msgPara, "L: p:%d, a:%s, nt:IN%s%s, es-cci:%s, es-ccd:%s:%d\r\n", l->p, l->codec
			            , (l->ecDisable)? ", e:off" : "", (l->ssDisable)? ", s:off" : "", l->esCci, l->esCcd.domain, l->esCcd.port);		
            }
			else
			{
                sprintf(msgPara, "L: p:%d, a:%s, nt:IN%s%s, es-cci:%s\r\n", l->p, l->codec
			            , (l->ecDisable)? ", e:off" : "", (l->ssDisable)? ", s:off" : "", l->esCci);
			}
		}
		else
		{
            sprintf(msgPara, "L: p:%d, a:%s, nt:IN%s%s\r\n", l->p, l->codec
			        , (l->ecDisable)? ", e:off" : "", (l->ssDisable)? ", s:off" : "");
		}
    }
    
    return 0;
}

int mgcp_para_con_mode_encode(MGCP_M *m, char *msgPara)
{
    if ((m == NULL) ||
        (msgPara == NULL))
        return -1;
    
    if (m->mode > MGCP_CON_MODE_SENDRECV)
        return -1;
    
    sprintf(msgPara, "M: %s\r\n", mgcpConModeToStr[m->mode]);
    
    return 0;
}

int mgcp_para_signal_req_encode(WORD port, MGCP_S *s, char *msgPara)
{
    char    str[32];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (s == NULL) ||
        (msgPara == NULL))
        return -1;
    
    if (s->pkg >= MGCP_PACKAGE_MAX)
        return -1;


    if (s->signal > mgcpMaxPkgSig[s->pkg])
        return -1;
    
    
    if (mgcp_create_req_id(port, s->reqId) < 0)
        return -1;
    
    sprintf(msgPara, "X: %s\r\n", s->reqId);
    
    if (s->signal == MGCP_PACKAGE_SIG_NONE)
        strcat(msgPara, "S:\r\n");
    else
    {
        sprintf(str, "S: %s/%s\r\n", mgcpPkgToStr[s->pkg], mgcpAalnSigToStr[s->pkg][s->signal]);
        strcat(msgPara, str);
    }
    
    return 0;
}

int mgcp_para_request_event_encode(WORD port, MGCP_R *r, char *msgPara)
{
    char    str[32];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||(r == NULL) ||
        (msgPara == NULL))
        return -1;
        
        if (r->pkg >= MGCP_PACKAGE_MAX)
            return -1;

    if (r->event > mgcpMaxPkgEvent[r->pkg])
        return -1;      
            
    if (mgcp_create_req_id(port, r->reqId) < 0)
        return -1;
    
    sprintf(msgPara, "X: %s\r\n", r->reqId);                    
                            
    sprintf(str, "R: %s/%s\r\n", mgcpPkgToStr[r->pkg], mgcpEntToStr[r->pkg][r->event]);
    strcat(msgPara, str);       
            
    return 0;   
}

int mgcp_para_observed_ent_encode(WORD port, MGCP_O *o, char *msgPara)
{
    char    str[32];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||(o == NULL) ||
        (msgPara == NULL))
        return -1;
        
    if (o->package >= MGCP_PACKAGE_MAX)
        return -1;

    if (o->event > mgcpMaxPkgEvent[o->package])
        return -1;          
        
    if (mgcp_create_req_id(port, o->reqId) < 0)
        return -1;
    sprintf(msgPara, "X: %s\r\n", o->reqId);            
        
    sprintf(str, "O: %s/%s\r\n", mgcpPkgToStr[o->package], mgcpEntToStr[o->package][o->event]); 
    strcat(msgPara, str);       
            
    return 0;
}


int mgcp_para_restart_mod_encode(MGCP_RM *rm, char *msgPara)
{
    if ((NULL == rm)||(NULL == msgPara))
        return -1;
        
    if (rm->rm >= MGCP_REST_MOD_MAX)
        return -1;
        
    sprintf(msgPara, "%s", mgcpRestModToStr[rm->rm]);
            
    return 0;
}

int mgcp_para_restart_delay_encode(MGCP_RD *rd, char *msgPara)
{
    if ((NULL == rd)||(NULL == msgPara))
        return -1;
        
        sprintf(msgPara, "RD: %d\r\n", rd->rd);
        
    return 0;
}
/**/
int mgcp_cmd_crcx_para_encode(WORD port, char *msgText)
{
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    DWORD       flag;
    char        msgPara[128];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (msgText == NULL))
        return -1;
    
    trans = &mgcpPort[port];
    para = &trans->para;
    flag = para->flag;
    
    if ((flag & MGCP_PARA_FLAG_C) == 0)
        return -1;
    if (mgcp_para_call_id_encode(&para->c, msgPara) < 0)
        return -1;
    strcat(msgText, msgPara);
    
    if ((flag & MGCP_PARA_FLAG_L) != 0)
    {
        if (mgcp_para_local_con_opt_encode(&para->l, msgPara, flag) < 0)
            return -1;
        strcat(msgText, msgPara);
    }
    
    if ((flag & MGCP_PARA_FLAG_M) == 0)
        return -1;
    if (mgcp_para_con_mode_encode(&para->m, msgPara) < 0)
        return -1;
    strcat(msgText, msgPara);
    
    return 0;
}

int mgcp_cmd_mdcx_para_encode(WORD port, char *msgText)
{
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    DWORD       flag;
    char        msgPara[128];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (msgText == NULL))
        return -1;
    
    trans = &mgcpPort[port];
    para = &trans->para;
    flag = para->flag;
    
    if ((flag & MGCP_PARA_FLAG_C) == 0)
        return -1;
    if (mgcp_para_call_id_encode(&para->c, msgPara) < 0)
        return -1;
    strcat(msgText, msgPara);
    
    if ((flag & MGCP_PARA_FLAG_I) == 0)
        return -1;
    if (mgcp_para_con_id_encode(&para->i, msgPara) < 0)
        return -1;
    strcat(msgText, msgPara);
    
    if ((flag & MGCP_PARA_FLAG_L) != 0)
    {
        if (mgcp_para_local_con_opt_encode(&para->l, msgPara, flag) < 0)
            return -1;
        strcat(msgText, msgPara);
    }
    
    if ((flag & MGCP_PARA_FLAG_M) != 0)
    {
        if (mgcp_para_con_mode_encode(&para->m, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }
    
    if ((flag & MGCP_PARA_FLAG_S) != 0)
    {
        if (mgcp_para_signal_req_encode(port, &para->s, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }   
    
    return 0;
}

int mgcp_cmd_dlcx_para_encode(WORD port, char *msgText)
{
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    DWORD       flag;
    char        msgPara[128];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (msgText == NULL))
        return -1;
    
    trans = &mgcpPort[port];
    para = &trans->para;
    flag = para->flag;
    
    if ((flag & MGCP_PARA_FLAG_C) != 0)
    {
        if (mgcp_para_call_id_encode(&para->c, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }
    
    if ((flag & MGCP_PARA_FLAG_I) != 0)
    {
        if (mgcp_para_con_id_encode(&para->i, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }
    
    if ((flag & MGCP_PARA_FLAG_S) != 0)
    {
        if (mgcp_para_signal_req_encode(port, &para->s, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }
    
    return 0;
}

int mgcp_cmd_rqnt_para_encode(WORD port, char *msgText)
{
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    DWORD       flag;
    char        msgPara[128];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (msgText == NULL))
        return -1;
    
    trans = &mgcpPort[port];
    para = &trans->para;
    flag = para->flag;
    
    if ((flag & MGCP_PARA_FLAG_S) != 0)
    {
        if (mgcp_para_signal_req_encode(port, &para->s, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }

    if ((flag & MGCP_PARA_FLAG_R) != 0)
    {
        if (mgcp_para_request_event_encode(port, &para->r, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }   
    
    return 0;
}

int mgcp_cmd_ntfy_para_encode(WORD port, char *msgText)
{
    
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    DWORD       flag;
    char        msgPara[128];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (msgText == NULL))
        return -1;
    
    trans = &mgcpPort[port];
    para = &trans->para;
    flag = para->flag;

    if ((flag & MGCP_PARA_FLAG_O) == 0)
            return -1;
    if (mgcp_para_observed_ent_encode(port, &para->o, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
        
    return 0;   
}

int mgcp_cmd_auep_para_encode(WORD port, char *msgText)
{

    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (msgText == NULL))
        return -1;
    
    return 0;   
        
}

int mgcp_cmd_rsip_para_encode(WORD port, char *msgText)
{
    
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    DWORD       flag;
    char        msgPara[128];
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (msgText == NULL))
        return -1;
    
    trans = &mgcpPort[port];
    para = &trans->para;
    flag = para->flag;
    if ((flag & MGCP_PARA_FLAG_RM) == 0)
            return -1;
    if (mgcp_para_restart_mod_encode(&para->rm, msgPara) < 0)
            return -1;
        sprintf(msgText, "RM: %s\r\n", msgPara);
    
    if ((flag & MGCP_PARA_FLAG_RD) != 0)
    {
       if (mgcp_para_restart_delay_encode(&para->rd, msgPara) < 0)
            return -1;
        strcat(msgText, msgPara);
    }
    return 0;   
    
}

int mgcp_send_msg(WORD port, BYTE cmdRes)
{
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    MGCP_SL     *sl;
    DWORD       flag;
    BYTE    cmd;
    WORD        len;
    char        endPointId[16];
    char        *msgText = mgcpSdMsg.msgContent;
    char        resPara[256];
    
    if (port >= MGCP_MAX_NUM_OF_PORT)
        return -1;
    
    msgText[MAX_CONTENT_LEN - 1] = '\0';
    
    trans = &mgcpPort[port];
    
    if (cmdRes == MGCP_COMMAND)
    {
        cmd = trans->cmd;
        para = &trans->para;
        flag = para->flag;
        sl = &para->sl;
        
        if ((flag & MGCP_PARA_FLAG_SL) == 0)
        {
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
                sprintf(mgcpAsciTempBuf, "MGCP_COMMAND have no sl flag\r\n");
                mgcp_log_err(mgcpAsciTempBuf);
            }               
            return -1;
        }
        
        if ((cmd < MGCP_CMD_CRCX) || (cmd > MGCP_CMD_RSIP))
        {
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
                sprintf(mgcpAsciTempBuf, "cmd is unknown\r\n");
                mgcp_log_err(mgcpAsciTempBuf);
            }                   
            return -1;
        }
        
        if (mgcp_ep_id_encode(sl, endPointId) < 0)
        {
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
                 sprintf(mgcpAsciTempBuf, "ep id encode fault\r\n");
                 mgcp_log_err(mgcpAsciTempBuf);
            }           
            return -1;
        }
        
        // Start Line
        if (0 == strcmp(sl->mgName, ""))
        {
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
                 sprintf(mgcpAsciTempBuf, "no domain name\r\n");
                 mgcp_log_err(mgcpAsciTempBuf);
            }           
            return -1;          
        }   
        
        sprintf(msgText, "%s %ld %s@%s MGCP 1.0\r\n", mgcpCmdToStr[cmd], trans->transId, endPointId, sl->mgName);
        
        // Parameters
        switch (cmd)
        {
        case MGCP_CMD_CRCX:
            if (mgcp_cmd_crcx_para_encode(port, msgText) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
          sprintf(mgcpAsciTempBuf, "crcx para encode fault\r\n");
          mgcp_log_err(mgcpAsciTempBuf);
        }                   
                return -1;
            }
            break;
        case MGCP_CMD_MDCX:
            if (mgcp_cmd_mdcx_para_encode(port, msgText) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
          sprintf(mgcpAsciTempBuf, "mdcx para encode fault\r\n");
          mgcp_log_err(mgcpAsciTempBuf);
        }                   
                return -1;
            }
            break;
        case MGCP_CMD_DLCX:
            if (mgcp_cmd_dlcx_para_encode(port, msgText) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
          sprintf(mgcpAsciTempBuf, "dlcx para encode fault\r\n");
          mgcp_log_err(mgcpAsciTempBuf);
        }                   
                return -1;
            }
            break;
        case MGCP_CMD_RQNT:
            if (mgcp_cmd_rqnt_para_encode(port, msgText) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
              {
                 sprintf(mgcpAsciTempBuf, "rqnt para encode fault\r\n");
                 mgcp_log_err(mgcpAsciTempBuf);
              }                 
                return -1;
            }
            break;
        case MGCP_CMD_NTFY:
            if (mgcp_cmd_ntfy_para_encode(port, msgText) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
          sprintf(mgcpAsciTempBuf, "ntfy para encode fault\r\n");
          mgcp_log_err(mgcpAsciTempBuf);
        }                   
                return -1;
            }
            break;
        case MGCP_CMD_AUEP:
            if (mgcp_cmd_auep_para_encode(port, msgText) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
          sprintf(mgcpAsciTempBuf, "auep para encode fault\r\n");
          mgcp_log_err(mgcpAsciTempBuf);
        }                   
                return -1;
            }
            break;
        case MGCP_CMD_RSIP:
            if (mgcp_cmd_rsip_para_encode(port, msgText) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
        {
          sprintf(mgcpAsciTempBuf, "rsip para encode fault\r\n");
          mgcp_log_err(mgcpAsciTempBuf);
        }                   
                return -1;
            }
            break;
        default:
            break;
        }
        
        len = strlen(msgText);
        
        // SDP
        if ((flag & MGCP_PARA_FLAG_SDP) != 0)
        {
            strcat(msgText, "\r\n");
            len += 2;
            if (pub_sdp_encode(&para->sdp, msgText + len, flag) < 0)
            {
              if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
              {
                sprintf(mgcpAsciTempBuf, "mgcp send cmd: pub sdp encode fault\r\n");
                mgcp_log_err(mgcpAsciTempBuf);
              }             
              return -1;
            }
            len += strlen(msgText + len);
        }
    }
    else
    {
        para = &trans->para;
        flag = para->flag;
        sl = &para->sl;
        
        if ((flag & MGCP_PARA_FLAG_SL) == 0)
        {
            if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
            {
                sprintf(mgcpAsciTempBuf, "MGCP_RESPONSE have no sl flag\r\n");
                mgcp_log_err(mgcpAsciTempBuf);
            }             
            return -1;
        }       
        
        // Start Line
        sprintf(msgText, "%d %ld %s\r\n", sl->retCode, trans->transId, sl->desc);

        if (((trans->cmd == MGCP_CMD_CRCX) || (trans->cmd == MGCP_CMD_MDCX))&& (sl->retCode == 200))
        {
            if (trans->cmd == MGCP_CMD_CRCX)
            {
                sprintf(resPara, "I: %s\r\n", para->i.conId);
                strcat(msgText, resPara);
            }

            // SDP
            if ((flag & MGCP_PARA_FLAG_SDP) != 0)
            {
                strcat(msgText, "\r\n");
                
                len = strlen(msgText);
                
                if (pub_sdp_encode(&para->sdp, msgText + len, flag) < 0)
                {
                    if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
                    {
                        sprintf(mgcpAsciTempBuf, "mgcp send rsp: pub sdp encode fault\r\n");
                        mgcp_log_err(mgcpAsciTempBuf);
                    }
                    return -1;
                }
            }
        }     
        
        len = strlen(msgText);
    }
    
  if (((mgcpMonitorFg & MONITOR_ALL) == MONITOR_ALL) || ((mgcpMonitorFg | MONITOR_ERROR) == MONITOR_ALL))
  {      
      sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
      mgcp_asciout_proc(mgcpAsciTempBuf);
  }
  else if ((mgcpMonitorFg | MONITOR_MG0_MSG | MONITOR_MG1_MSG | MONITOR_MG2_MSG |MONITOR_ERROR) == MONITOR_ALL)
  {
    if ((mgcpMonitorFg & MONITOR_MG0_MSG) == 0)
    {
      if ((mgcpMonitorFg & MONITOR_MG1_MSG) == 0)
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2])))
           {
               sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
           }
        }
        else
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])))
           {
               sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
           }        
        }
      }
      else
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0]))  
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2])))
           {
               sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
           }
        }
        else
        {
           if (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0]))
           {
               sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
           }        
        }      
      }
    }
    else
    {
      if ((mgcpMonitorFg & MONITOR_MG1_MSG) == 0)
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if ((0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])) 
                && (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2])))
           {
               sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
           }
        }
        else
        {
           if (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1]))
           {
               sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
           }        
        }
      }
      else
      {
        if ((mgcpMonitorFg & MONITOR_MG2_MSG) == 0)
        {
           if (0 != strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2]))
           {
               sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
               mgcp_asciout_proc(mgcpAsciTempBuf);
           }
        }      
      }    
    }
  }
  else if (((mgcpMonitorFg & MONITOR_MG0_MSG) == MONITOR_MG0_MSG) 
            || ((mgcpMonitorFg & MONITOR_MG1_MSG) == MONITOR_MG1_MSG) 
            || ((mgcpMonitorFg & MONITOR_MG2_MSG) == MONITOR_MG2_MSG))
  {
    if ((((mgcpMonitorFg & MONITOR_MG0_MSG) == MONITOR_MG0_MSG) && (0 == strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[0])))
         || (((mgcpMonitorFg & MONITOR_MG1_MSG) == MONITOR_MG1_MSG) && (0 == strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[1])))
         || (((mgcpMonitorFg & MONITOR_MG2_MSG) == MONITOR_MG2_MSG) && (0 == strcmp(mgcpPort[port].para.sl.mgName, dbgmgNamemg[2]))))
     {
         sprintf(mgcpAsciTempBuf, "Send Message: %s\r\n", msgText);
      
         mgcp_asciout_proc(mgcpAsciTempBuf);
     }   
  }
    
    
    mgcpSdMsg.msgDstIP      = para->ip;
    mgcpSdMsg.msgSrcPort    = para->localPort;
    mgcpSdMsg.msgDstPort    = para->peerPort;
    mgcpSdMsg.msgLength     = len;
    
    iptrDirectSendMsg(mgcpSdMsg);
    
    return 0;
}

int mgcp_send_rsp(WORD port, BYTE retCodeIndex)
{
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    MGCP_SL     *sl;
//  WORD tPort;
    
    if ((port >= MGCP_MAX_NUM_OF_PORT) ||
        (retCodeIndex >= MGCP_MAX_RET_CODE_INDEX))
    {
      if ((mgcpMonitorFg & MONITOR_ERROR) == MONITOR_ERROR)
    {
      sprintf(mgcpAsciTempBuf, "mgcp_send_rsp: port or retCodeIndex fault\r\n");
      mgcp_log_err(mgcpAsciTempBuf);
    }           
        return -1;
    }
    
    trans = &mgcpPort[port];
    para = &trans->para;
    sl = &para->sl;

    para->flag = MGCP_PARA_FLAG_SL;
    
    sl->cmdRes = MGCP_RESPONSE;
    sl->retCode = mgcpRetCode[retCodeIndex].retCode;
    strcpy(sl->desc, mgcpRetCode[retCodeIndex].desc);
    
    if (mgcp_send_msg(port, MGCP_RESPONSE) < 0)
        return -1;
    
    return 0;
}

int mgcp_send_incmd_rsp(DWORD transId, BYTE retCodeIndex)
{
    MGCP_PORT   *trans;
    MGCP_PARA   *para;
    
    trans = &mgcpPort[0];
    para = &trans->para;
         
    trans->transId = transId;
    para->ip = mgcpRvMsg.msgSrcIP;
    para->peerPort = mgcpRvMsg.msgSrcPort;
    para->localPort = mgcpRvMsg.msgDstPort;
        
    if (mgcp_send_rsp(0, retCodeIndex) < 0)
        return -1;
    
    return 0;   
}
