/* putenv.c - yet another implementation of the System V library routine.
   This code is in the public domain and may be freely changed and distributed.
   Written March, 1989 by Michael J. Haertel */

extern char *malloc(), *realloc();
extern char **environ;

static unsigned int envsize, envalloc, init;

static int
initialize()
{
	char **p;
	int i;

	for (p = environ, i = 0; *p; ++i, ++p)
		;
	envsize = i;

	envalloc = 1;
	while (envalloc <= i)
		envalloc *= 2;
	
	p = (char **) malloc(envalloc * sizeof (char *));
	if (! p)
		return 0;
	
	for (i = 0; i <= envsize; ++i)
		p[i] = environ[i];
	
	environ = p;
	init = 1;
	return 1;
}

static int
match(s, t)
	register char *s, *t;
{
	while (*s && *s != '=' && *s == *t)
		++s, ++t;
	if (*s == '=' && *s == *t)
		return 1;
	return 0;
}

int
putenv(s)
	char *s;
{
	int i;
	char **p;

	if (!init && !initialize())
		return 0;
	
	for (i = 0; i < envsize; ++i)
		if (match(s, environ[i])) {
			environ[i] = s;
			return 1;
		}
	
	if (i >= envalloc) {
		p = (char **) realloc((char *) environ,
				      envalloc * 2 * sizeof (char **));
		if (!p)
			return 0;
		environ = p;
		envalloc *= 2;
	}

	environ[i] = s;
	++envsize;
	return 1;
}
