/* Copyright (C) 1997-1999 NEC Research Institute.
 * Please see the file LICENSE for license information.
 */
#include "mlton-lib.h"

#if defined(_WIN32)
#else
struct tms MLTON_tms;
#endif

struct stat MLTON_stat;

struct utimbuf MLTON_utimbuf;

#if defined(_WIN32)
#else
struct utsname MLTON_utsname;

struct flock MLTON_flock;

struct termios MLTON_termios;
#endif

/* Right now this is messy because mlton has no way of dealing with unsigned 
 * shorts (i.e. gid_t).
 */
#if defined(_WIN32)
#else
int MLTON_getgroups(pointer groups) {
	int i, result;
	gid_t groupList[MLTON_numgroups];
	
	result = getgroups(MLTON_numgroups, groupList);
	
	for (i = 0; i < result; i++)
		((uint*)groups)[i] = groupList[i];
	
	return result;
}
#endif

#if defined(_WIN32)
//FIXME: I don't know how this is supposed to work, but
// this windows function might be useful:
// WinExec(name, SW_SHOWNORMAL);

// Or for a less simple version, which I don't know how really works:
//CreateProcess(name, NULL, NULL, NULL, FALSE, 0,
//              NULL, NULL,
//              NULL/* May not be NULL */,
//              NULL/* May not be NULL */);
#else
int MLTON_exec(pointer p, pointer a) {
	char *path, *saved, **args;
	int n, result;

	path = (char*)p;
	args = (char**)a;
	n = GC_arrayNumElements(args) - 1;
	saved = args[n];
	args[n] = (char*)NULL;
	result = execv(path, args);
	/* exec failed */
	args[n] = saved;
	return result;
}

int MLTON_exece(pointer p, pointer a, pointer e) {
	char *path, *asaved, *esaved, **args, **env;
	int an, en, result;

	path = (char*)p;
	args = (char**)a;
	env = (char**)e;
	an = GC_arrayNumElements(args) - 1;
	asaved = args[an];
	en = GC_arrayNumElements(env) - 1;
	esaved = env[en];
	args[an] = (char*)NULL;
	env[en] = (char*)NULL;
	result = execve(path, args, env);
	/* exece failed */
	args[an] = asaved;
	env[en] = esaved;
	return result;
}

int MLTON_execp(pointer f, pointer a) {
	char *file, *saved, **args;
	int n, result;

	file = (char*)f;
	args = (char**)a;
	n = GC_arrayNumElements(args) - 1;
	saved = args[n];
	args[n] = (char*)NULL;
	result = execvp(file, args);
	/* execp failed */
	args[n] = saved;
	return result;
}
#endif
