/*
 * Routine to convert a UNIX-style path to an AmigaDOS path.
 * A UNIX-style path is understood here as follows:
 * 
 * 	leading . means current dir; like "", but filled in explicitly
 * 	../ means /
 * 	..  means /
 * 
 * Written as part of UnixDirs2, a (to be written) system patch which allows
 * use of UNIX-style paths everywhere.
 * 
 * Martin W. Scott,  8 January 1993
 */
#include <exec/types.h>
#include <exec/execbase.h>
#include <dos/dos.h>
#include <dos/dosextens.h>
#include <string.h>
#include <proto/dos.h>
#include <proto/exec.h>

extern struct ExecBase *SysBase;

/* insert $cwd into s, return pointer to next free char */
char *
insertcwd(char *s, LONG len)
{
	geta4();

	if (NameFromLock(((struct Process *)(SysBase->ThisTask))->pr_CurrentDir, s, len))
	{
		while (*s)
			s++;
	}
	return s;
}

/* adjust path from UNIX-style to Amiga-style */
/* TO DO: length checking when building new path */
BOOL
adjustpath(char *path, char *newpath, LONG len)
{
	char *s, *t;
#ifdef DEBUG
	char *origpath = path;
#endif
	geta4();
	s = newpath;

	if (path == NULL)	/* bypass */
		return FALSE;

	if (t = strchr(path, ':'))		/* check for ':' in path */
	{
		t++;				/* copy device component */
		while (path < t)
			*s++ = *path++;
	}
	else if (path[0] == '.')		/*** translate '.' to $cwd ***/
	{
		if (!path[1])			/* only "." */
		{
			s = insertcwd(s, len);
			path++;			/* path[0] == '\0' - STOP */
		}
		else if (path[1] == '/')	/* initial component is $cwd */
		{
			s = insertcwd(s, len);
			if (*(s-1) != ':')
				*s++ = '/';	/* copy '/', increment pointers */
			path += 2;
		}
	}

	while (path[0])			/*** copy remainder of path ***/
	{
		if (path[0] == '.' && path[1] == '.')
		{
			if (path[2] == '/')	/* just skip "..", copying '/' */
			{
				path += 2;
				*s++ = *path++;
			}
			else if (!path[2])	/* append '/' and stop */
			{
				path += 2;
				*s++ = '/';
			}
			else *s++ = *path++;
		}
		else *s++ = *path++;
	}
	*s = '\0';

	return TRUE;
}

#ifdef TEST

void
main(int argc, char **argv)
{
	UWORD i;

	for (i = 1; i < argc; i++)
	{
		char *buf;

		if (buf = AllocMem(512, 0L))
		{
			adjustpath(argv[i], buf, 512);
			printf("%s --> %s\n", argv[i], buf);
			FreeMem(buf, 512);
		}
	}

} /* main */

#endif