// This file is part of The New Aspell
// Copyright (C) 2001, 2006 Free Software Foundation, Inc. 
// under the GNU LGPL license version 2.0 or 2.1.  
// You should have received a copy of the LGPL
// license along with this library if you did not you can find
// it at http://www.gnu.org/.

// Copyright (C) 2007 by Nicolas Hatier under the same terms

#include <sys/types.h>
#include <io.h>
#include "dirent.h"
#include "string.hpp"

struct dirstream
{
   intptr_t handle;     
   _finddata_t data;    
   bool do_next;	      
};

void normalize(char * name, int max)
{
   if (name)
   {
      while(*name && max>0)
      {
         if (*name == '\\')
            *name = '/';
         ++name;
         --max;
      }
   }
}

DIR * opendir (const char * name)
{
   dirstream * dir;
   intptr_t hnd;
   
   _finddata_t find;

   if (!name || !*name)
      return NULL;

   acommon::String file(name);
   normalize((char*)file.str(), file.size());

   if (file.back() != '/')
      file += "/";
   file += "*";
   
   if ((hnd = _findfirst(file.str(), &find)) == -1)
      return NULL;

   dir = new dirstream;   
   dir->handle = (int) hnd;   
   dir->do_next = false;
   memcpy (&dir->data, &find, sizeof (_finddata_t));
   return dir;
}

dirent * readdir (DIR * in_dir)
{
   static dirent entry;

   dirstream * dir = ((dirstream*)in_dir);

   if (dir->do_next)
   {
      if (_findnext(dir->handle, &dir->data))
         return NULL;
   }

   strncpy (entry.d_name, dir->data.name, sizeof (entry.d_name));
   normalize(entry.d_name, sizeof(entry.d_name));
   dir->do_next = true;
   return &entry;
}

int closedir (DIR * in_dir)
{
   dirstream * dir = ((dirstream*)in_dir);   
   delete dir;
   return _findclose(dir->handle) ? 0 : -1;
}
