/*
 * libnqs/queue/pipeqdest.c
 * 
 * DESCRIPTION:
 *
 *	Return the machine-id, queue name, and retry count values for
 *	the specified pipe queue destination (as defined in the environment
 *	of a pipe queue server).
 *
 *	Original Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	May 8, 1986.
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>
#include <stdlib.h>

/*** pipeqdest
 *
 *	char *pipeqdest():
 *
 *	Return the machine-id, time spent in retry state, and queue name
 *	values for the specified pipe queue destination (as defined in the
 *	environment of a pipe queue server).
 *
 *	Returns:
 *		A pointer to the name of the destination queue (if
 *		the specified queue destination exists).  Otherwise,
 *		(char *) 0 is returned.
 */
char *pipeqdest (
	int destno,		/* Destination number [1..n] */
	Mid_t *destmid,		/* Machine-id of destination */
	long *retrytime)	/* Time spent in retry state */
{
	char envvarname [5];		/* Environment var name */
	register char *dest;		/* Ptr to dest environment var */
	register unsigned long ulong;	/* For scanning */
	register char ch;		/* Scan character */
        register short neg;

  	assert (destmid   != NULL);
  	assert (retrytime != NULL);
  
	if ((destno < 1) || (destno > 1000)) {
		return ((char *) 0);	/* No such destination */
	}
	sprintf (envvarname, "D%03d", destno-1);
	dest = getenv (envvarname);	/* Get the environment var for dest */
	if (dest == (char *) 0) {
		return ((char *) 0);	/* No such destination */
	}
	ch = *dest;			/* Get scan character */
	while (ch == ' ') {		/* Scan any whitespace */
		ch = *++dest;
	}
        if (ch == '-') {                /* Scan any for negative */
                ch = *++dest;
                neg = -1;
        }
        else
                neg =1;

	ulong = 0;
	while (ch >= '0' && ch <= '9') {/* Scan destination machine-id */
		ulong *= 10;
		ulong += ch - '0';
		ch = *++dest;
	}
	*destmid = ulong * neg;
	while (ch == ' ') {		/* Scan any whitespace */
		ch = *++dest;
	}
	ulong = 0;
	while (ch >= '0' && ch <= '9') {/* Scan destination machine-id */
		ulong *= 10;
		ulong += ch - '0';
		ch = *++dest;
	}
	*retrytime = ulong;
	while (ch == ' ') {		/* Scan any whitespace */
		ch = *++dest;
	}
	return (dest);			/* Return pointer to queue name */
}
