/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/

#include <windows.h>
#include <stdlib.h>
#include "machine/include.h"

DIR *opendir(const char *dirname){
DIR *ret;
char filter[MAX_PATH+1];
	
	if(dirname[strlen(dirname)-1] == '\\' || 
		dirname[strlen(dirname)-1] == '/'){
		wsprintf(filter, "%s*.*", dirname);
	}
	else{
		wsprintf(filter, "%s\\*.*", dirname);
	}
	
	ret = (DIR*)calloc(sizeof(DIR), 1);
	ret->h = FindFirstFile(filter, &ret->fd);
	if(ret->h == INVALID_HANDLE_VALUE){
		free(ret);
		return NULL;
	}
	else{
		ret->firsttime = 1;
		return ret;
	}
}

struct dirent *readdir(DIR *dirp)
{
	if(!dirp)
		return NULL;
	if(dirp->h == INVALID_HANDLE_VALUE)
		return NULL;
	if(dirp->firsttime == 1){
		dirp->firsttime = 0;
	}
	else{
		if(!FindNextFile(dirp->h, &dirp->fd)){
			return NULL;
		}
	}
	dirp->de.d_ino = 1;
	dirp->de.d_name = dirp->fd.cFileName;
	dirp->de.d_reclen = sizeof(struct dirent);
	return &dirp->de;
}

int closedir(DIR *dirp){
	if(!dirp){
		return -1;
	}
	FindClose(dirp->h);
	free(dirp);
	return 0;
}

