/* simple opendir() etc. for Win32 */

#include <string.h>
#include <ctype.h>
#define strcmp stricmp
#include <stdlib.h>

#include <io.h>

#include <ndir.h>

DIR *opendir(const char *name)
{
	char localname[_MAX_NAME];
	DIR *rval = malloc(sizeof(DIR));
	strcpy(localname,name);
        strcat(localname,"\\*.*");
	if (rval == NULL)
                return NULL;
        if ((rval->handle = _findfirst(localname,&rval->dta)) == -1)
        	return free(rval), NULL;
	rval->first = 1;
	return rval;
}

int closedir(DIR *x)
{
  	_findclose(x->handle);
	free(x);
	return 0;
}

struct direct *readdir(DIR *thisdir)
{
        if(!thisdir->first)
	{
                if(_findnext(thisdir->handle, &thisdir->dta) != 0)
			return NULL;
	} else
                thisdir->first = 0;
        strcpy(thisdir->current.d_name,thisdir->dta.name);
	thisdir->current.d_namlen = strlen(thisdir->current.d_name);
	/* thisdir->current.d_name[13] = '\0'; */
	return &thisdir->current;
}

#ifdef TEST
void main(void)
{
  DIR *d = opendir(".");
  struct direct *f;
  
  if (d)
    while ((f = readdir(d)) != NULL)
      printf(">%s<\n", f->d_name);
}
#endif
