#include <stddef.h>
#include <stdlib.h>	/* both of these added for malloc() */
#include <limits.h>
#include <errno.h>
#include <osbind.h>
#include "lib.h"

/*******************************************************************
getcwd: returns current working directory. By ERS.
This routine is in the public domain.
********************************************************************/

extern int __mint;
extern char _rootdir;	/* in main.c: user's preferred root directory */

char *getcwd(buf, size)
char *buf; int size;
{
	char _path[PATH_MAX];
/* sometimes the GCC optimizer is too clever; it doesn't know that
   Dgetpath(path, 0) can change the stuff path points to
 */
	volatile char *path;
	char drv;

	if (!buf)
		if (!(buf = (char *) malloc((size_t)size)))
			return NULL;

	drv = Dgetdrv() + 'a';
	_path[0] = drv;
	_path[1] = ':';
	_path[2] = '\0';
	path = _path + 2;
	
	(void)Dgetpath(path, 0);

	if (_rootdir && drv == _rootdir) {
		if (!*path) {
			path[0] = '\\';
			path[1] = '\0';
		}
		_dos2unx((char *)path, buf);
		return buf;
	}
	_dos2unx(_path, buf);	/* convert DOS filename to unix */
	return buf;
}

/*
 * char *getwd(char *buf)
 *	return cwd in buf
 */
char *getwd(buf)
char *buf;
{
	return getcwd(buf, PATH_MAX);
}
