
/****** vartools/CreatePath ***************************************************
*
*  NAME
*		CreatePath -- "makedirs" whole path
*
*  SYNOPSIS
*		lock = CreatePath(name)
*
*		BPTR CreatePath(STRPTR)
*
*  FUNCTION
*		Creates a new dir in given path. If it's parent doesn't exist - creates
*		him. And so on. Unlike CreateDir() returns shared lock instead of
*		exclusive one! If given path exists - returns shared lock on it.
*
*  INPUTS
*		name - null-terminated string
*
*  RESULT
*		shared lock on most-inner created directory or NULL for error
*
*	NOTE
*		Requires Kickstart 3.0 (V39) - uses exec's pools.
*
*	BUGS
*		Due to a bug in PathPart() doesn't handles paths like "foo/bar//"
*		(two slashes together).
*
*	SEE ALSO
*		dos.library/CurrentDir()
*
******************************************************************************/

#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>

#include <proto/exec.h>
#include <proto/dos.h>

#include <string.h>

static BPTR createloop(APTR, STRPTR);

BPTR CreatePath(STRPTR path)
{
	BPTR	curlock, lock;
	APTR	pool;

	if (lock = Lock(path, ACCESS_READ))
		return lock;

	if (!(pool = CreatePool(MEMF_ANY, 512, 512)))
		return NULL;

	/* save current dirlock */
	curlock = CurrentDir(0);
	lock = DupLock(curlock);
	CurrentDir(lock);

	lock = createloop(pool, path);

	UnLock(CurrentDir(curlock));
	
	DeletePool(pool);

	return lock;
}

static BPTR createloop(APTR pool, STRPTR path)
{
	UBYTE	*buf, *t;
	BPTR	lock;

	if (lock = Lock(path, ACCESS_READ))
		return lock;

	buf = AllocPooled(pool, strlen(path)+1);

	strcpy(buf, path);
	t = PathPart(buf);
	if (!*t)
		return NULL;

	*t = 0;


	lock = createloop(pool, buf);

	if (!lock)
		return NULL;

	UnLock(CurrentDir(lock));

	lock = CreateDir(FilePart(path));
	if (lock) ChangeMode(CHANGE_LOCK, lock, ACCESS_READ);
	return lock;
}

