/* $Id: compat.c,v 1.3 1998/01/26 11:57:48 ek Exp $
 * This is a reduced portable version of snprintf, implemmented for
 * ssyslog. It supports only %s and %d with flags.
 *
 * Author: Ariel Futoransky
 */

#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#if __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif

extern int sys_nerr;
extern char *sys_errlist[];

#ifdef NO_DAEMON
int
daemon (a, b)
		 int a, b;
{
	switch (fork ())
		{
		case -1:
			return -1;
		case 0:
			if (!b)
				{
					close (0);
					close (1);
					close (2);
					if ((b = open ("/dev/null", O_RDWR)) >= 0)
						{
							dup2 (b, 0);
							dup2 (b, 1);
							dup2 (b, 2);
						}
				}
			if (!a)
				{
					chdir ("/");
				}
			return (0);
		default:
			exit (0);
		}
}
#endif
#ifdef NO_STRERROR
char *
strerror (int i)
{
	if (i < 0 || i > sys_nerr)
		return ("unknown");

	return (sys_errlist[i]);
}
#endif

#ifdef NO_SNPRINTF
int
snprintf (char *str, size_t n, char *fmt,...)

{
	va_list ap;
	int padding, max;
	char *x;
	char buf[20];
	int l;
	int c = 0;
	int pright = 1;	

	if ((int) n < 1)
		return (EOF);



#if __STDC__
	va_start (ap, fmt);
#else
	va_start (ap);
#endif
	while (*fmt && n > 0)
		{
			switch (*fmt)
				{
				case '%':
					fmt++;
					if (*fmt == '%')
						{
							*(str++) = *(fmt++);
							n--;
							c++;
							break;
						}
					padding = 0;
					max = 0;
					if (*fmt == '-')
						{
							pright = 0;
							fmt++;
						}
					if (*fmt == '.')
						{
							max = 1;
							fmt++;
						}
					while (*fmt >= '0' && *fmt <= '9')
						padding = padding * 10 + *(fmt++) - '0';

					if (*fmt == 's')
						{
							fmt++;
							x = va_arg (ap, char *);
						}
					else
						{
							x = buf;
							fmt++;
							l = va_arg (ap, int);
							sprintf (buf, "%d", l);
						}
					l = strlen (x);
					if (l > n)
					{
						l = n;
					} 

					if (max && padding && l > padding)
						l = padding;

					while (pright && (padding>l) && (n>0)) 
					{
						*(str++) = ' ';
						n--; padding--;	c++;
					}

					strncpy (str, x, l);
					str += l; 
					n -= l;
					c += l;
					if (padding && !pright)
						while ((l<padding) && (n > 0))
						{
							*(str++) = ' ';
							n--;
							c++;
							l++;
						}
							
					break;

				default:
					*(str++) = *(fmt++);
					n--;
					c++;
					break;
				}
		}
	if (n > 0)
		*str = '\0';

	va_end (ap);
	return (c);
}
#endif
