#include <stdio.h>
#include <string.h>
#include <dir.h >
#include <dos.h>
#include <sys\stat.h>

/* This routine returns the fullpath name from a relative path */

char *fullpath(char *relpath)
{
	static	char	full[MAXPATH];
	int drivenum ;
	char tempchar;
	register char *lead, *follow ;

	full[0] = '\0';

	drivenum = getdisk();

	if ((*relpath != '\0') && (relpath[1] == ':')) {
		drivenum = toupper(*relpath) - 'A' ;
		relpath += 2 ;
	}

	full[0] = (char) ('A' + drivenum) ;
	full[1] = ':' ;

	/* append relpath to fullpath/base */
	if (*relpath == '\\') {
		/* relpath starts at base */
		strcpy(full+2, relpath) ;
	} else {
		/* must get base path first */
		strcat (full,"\\");
		if (getcurdir(drivenum+1,full+3))
			return NULL;			/* terrible error */


		if ((*relpath != '\0'))
			strcat(full, "\\") ;

		strcat(full, relpath) ;
	}

	/* convert path to cannonical form */
	lead = full ;
	while(*lead != '\0') {
		/* mark next path segment */
		follow = lead ;
		lead = (char *) strchr(follow+1, '\\') ;
		if (!lead)
			lead = full + strlen(full) ;
		tempchar = *lead ;
		if (tempchar == '\\')
			tempchar = '\\';	/* make breaks uniform */
		*lead = '\0';

		/* "." segment? */
		if (strcmp(follow+1, ".") == 0) {
			*lead = tempchar ;
			strcpy(follow, lead);	/* remove "." segment */
			lead = follow ;
		}

		/* ".." segment? */
		else if (strcmp(follow+1, "..") == 0) {
			*lead = tempchar ;
			do {
				if (--follow < full)
					return NULL;
			} while (*follow != '\\') ;
			strcpy(follow, lead);		/* remove ".." segment */
			lead = follow ;
		}

		/* normal segment */
		else
			*lead = tempchar ;
	}
	if (strlen(full) == 2)	/* 'D:' or some such */
		strcat(full, "\\") ;

	/* shift to upper case */
	strupr(full) ;

	return full;
}

/* Return 1 if dir is a directory */
/* else 0 is returned             */

int isdir(char *dir)
{
	struct stat statbuf;

	if (stat(dir,&statbuf) == -1)
	{
		return 0;
	}
	else
	{
		if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
}

/* Create directory dir. If it already exsist do nothing */

void makedir(char *dir)
{
	if (!isdir(dir)) mkdir(dir);
}

/* Creat directory including all subdirectories needed */

void 	createdir(char *dir)
{
	char	*p;
	char	path[MAXPATH];
	char	tmp[MAXPATH];


	strcpy (path,fullpath(dir));
	p = strchr(path,'\\');

	p++;
	while ((p = strchr(p,'\\')) != NULL)
	{
		p++;
		strncpy (tmp,path,p-path-1);
		tmp[p-path-1] = '\0';
		makedir(tmp);
	}

	makedir(path);

}

