#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <dos/dosextens.h>
#include <inline/stubs.h>
#ifdef __OPTIMIZE__
#include <inline/exec.h>
#include <inline/dos.h>
#else
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#endif

#include <stdlib.h>

void AddMemToTC_MEMENTRY(void *rv);

/* we have a small problem with getenv():
   it returns a pointer to the contents of a environment-variable.
   We don't know when the user has used the variable, so we have
   to allocate memory for the environment-variable.
   As we don't want to lose memory, we add the memory to the
   TaskMemList, which is freed ad program termination.

   If a program calls genenv() for several times, the available
   memory will get less and less.

   All environment variables will get truncated to 100 characters
*/

char *getenv(const char *name)
{
	LONG len;
	UBYTE *mem;

	if( (mem=(char *)AllocVec(100,MEMF_PUBLIC|MEMF_CLEAR)))
	{
		len=GetVar((STRPTR) name, mem, 100, 0);
		if(len != -1)
		{
				/* memory will be freed at program termination */

			AddMemToTC_MEMENTRY(mem);

			return mem;
		}
		else
		{
			/* we had no success with our name */

			FreeVec(mem);
			return NULL;
		}
	}

	return NULL;
}

int setenv(const char *name, const char *value, int overwrite)
{
	UBYTE Buffer[100];

	if(!overwrite)
	if(GetVar((STRPTR) name, Buffer, 100, 0)==-1)
	{
		overwrite=1;
	}

	if(overwrite)
		if(SetVar((STRPTR) name, (STRPTR) value, strlen(value), 0))
			return 0;
		else
			return -1;
	else
		return 0;	/* we are successfull in doing nothing. Is this right ?*/
}

#if 0
int putenv(const char *string)
{
	/* ??? I don't know the contents vor value, see getenv.doc */
	return setenv(string, value, 1);
}
#endif

void unsetenv(const char *name)
{
	DeleteVar((STRPTR) name, 0);
}
