/**********************************************************************
**
** ports.c - handles the registration ports and the mapping from
**		logical port names to absolute port address.
**
**********************************************************************/

/*
 * $Log: ports.c,v $
 * Revision 1.3  1991/10/17  13:03:53  jplevyak
 * Added new debug message.
 *
 * Revision 1.2  1991/10/16  23:23:14  jplevyak
 * Added some debugging statements.
 *
 * Revision 1.1  1991/10/11  23:16:05  jefft
 * Initial revision
 *
 */

#include	<stdio.h>
#include	<string.h>

#include	"debug.h"


#define         NEW(type, count)        (type *)malloc(sizeof (type) * count)


typedef struct	PE  {
  struct PE	*next;
  char		*alias;
  char		*address;
  } PORT;


extern int      server_fd;


static PORT     *listhead = NULL;


char *getPortAddress(name)
  char  *name;
{
  PORT  *ptr = listhead;

  DBGMSG1( "getPortAddress: %s\n", name );
  while(ptr != NULL) {
    DBGMSG1( "getPortAddress checking %s\n", ptr->alias );
    if (strcasecmp(ptr->alias, name))
      ptr = ptr->next;
    else
      return ptr->address;
  }

  return NULL;
}



registerPort(regmsg)
  char  *regmsg;
{
  char	portname[128];
  int   len;
  PORT  *ptr;


  ptr = NEW(PORT, 1);

  strtok(regmsg, " ");				/* skip message id */

  strcpy(portname, strtok(NULL, " "));		/* process reference name */
  strcat(portname, ".");
  strcat(portname, strtok(NULL, " "));		/* port logical name */
  ptr->alias = strdup(portname);		/* create alias */

  ptr->address = strdup(strtok(NULL, " "));	/* absolute address */

  DBGMSG2( "registerPort: new port [%s] at [%s]\n", ptr->alias, ptr->address ); 

  ptr->next = listhead;
  listhead = ptr;
}


/* X work procedure to recieve registartion messages in background */
int recvRegMessages(unused)
  char  *unused;
{
  char  regmsg[1024];
  int   n;

  if (DTMrecvRegistration(server_fd, regmsg, sizeof regmsg))  {
    registerPort(regmsg);
    }

  return 0;             /* do not remove */
}


dump_ports()
{
  PORT  *ptr = listhead;

fprintf(stderr, "\n==============================\n");
  while (ptr != NULL)  {
    fprintf(stderr, "%s = %s\n", ptr->alias, ptr->address);
    ptr = ptr->next;
    }
}
