/*
	fileops - extended form of file operation functions which
				 convert any '/' seperators in the filename to '\' then call
	          the original library functions.

				 statx is not mapped in global.h
*/

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

static void path2dos(const char *path, char *newpath)
{
	const char *p 	= path;
	char *q 			= newpath;
	int  sep 		= 0;

	for ( ; *p; p++) { 							/* copy string							*/
		if ((*q = *p) == '/')					/* translate seperator				*/
			*q = '\\';							
		if (*q == '\\') {							/* suppress repeated seperators	*/
			if (!sep)
				q++;
			sep = 1;
		}
		else {
			sep =0;
			q++;
		}
	}
			
	*q = '\0';										/* string terminator					*/

	return;
}
	

FILE *fopenx(const char *name, const char *mode)
{
	char namex[FILENAME_MAX];					/* buffer for translated str  	*/

	path2dos(name, namex);						/* convert path						*/
	return fopen(namex, mode);					/* call fopen function				*/
}

int	removex(const char *name)
{
	char namex[FILENAME_MAX];					/* buffer for translated str  	*/

	path2dos(name, namex);						/* convert path						*/
	return remove(namex);						/* call remove function				*/
}

int	renamex(const char *old, const char *new)
{
	char oldx[FILENAME_MAX];				/* buffer for translated str  	*/
	char newx[FILENAME_MAX];				/* buffer for translated str  	*/

	path2dos(old, oldx);						/* convert path						*/
	path2dos(new, newx);
	return rename(oldx, newx);				/* call remove function				*/
}

int	openx(const char *name, int mode, int prot)
{
	char namex[FILENAME_MAX];					/* buffer for translated str  	*/

	path2dos(name, namex);						/* convert path						*/
	return open(namex, mode, prot);			/* call open function				*/
}

int	creatx(const char *name, int prot)
{
	char namex[FILENAME_MAX];					/* buffer for translated str  	*/

	path2dos(name, namex);						/* convert path						*/
	return creat(namex, prot);					/* call creat function				*/
}

int	unlinkx(const char *name)
{
	char namex[FILENAME_MAX];					/* buffer for translated str  	*/

	path2dos(name, namex);						/* convert path						*/
	return unlink(namex);						/* call unlink function				*/
}

int	accessx(const char *name, int mode)
{
	char namex[FILENAME_MAX];					/* buffer for translated str  	*/

	path2dos(name, namex);						/* convert path						*/
	return access(namex, mode);				/* call remove function				*/
}
	
int	mkdirx(const char *path)
{
	char pathx[FILENAME_MAX];					/* buffer for translated str		*/

	path2dos(path, pathx);						/* convert path						*/
	return mkdir(pathx, 0);						/* call mkdir function				*/
}

int	statx(const char *path, struct stat *statbuf)
{
	char pathx[FILENAME_MAX];

	path2dos(path, pathx);
	return stat(pathx, statbuf);
}
