/*
copyright (c) 2007-2012 Kazuki Iwamoto http://www.maid.org/ iwm@maid.org

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "dirent.h"
#include <tchar.h>
#include <errno.h>


TDIR *
topendir (const TCHAR *name)
{
  int i;
  DWORD dwResult;
  HANDLE hFind;
  LPTSTR lpszFile, lpszName;
  WIN32_FIND_DATA fnData;
  TDIR *nDir;

  if (!name)
    {
      errno = EFAULT;
      return NULL;
    }
  if (name[0] == '\0')
    {
      errno = ENOTDIR;
      return NULL;
    }
  lpszName = HeapAlloc (GetProcessHeap (), HEAP_ZERO_MEMORY,
                                        (lstrlen (name) + 1) * sizeof (TCHAR));
  lstrcpy (lpszName, name);
#ifdef UNICODE
  for (i = 0; lpszName[i] != '\0'; i++)
    if (lpszName[i] == '/')
      lpszName[i] = '\\';
#else /* not UNICODE */
  i = 0;
  while (lpszName[i] != '\0')
    if (IsDBCSLeadByteEx (CP_ACP, lpszName[i]))
      {
        i += 2;
      }
    else
      {
        if (lpszName[i] == '/')
          lpszName[i] = '\\';
        i++;
      }
#endif /* not UNICODE */
  dwResult = GetFullPathName (lpszName, 0, NULL, &lpszFile);
  if (dwResult <= 0)
    {
      HeapFree (GetProcessHeap (), 0, lpszName);
      errno = ENOTDIR;
      return NULL;
    }
  nDir = HeapAlloc (GetProcessHeap (), HEAP_ZERO_MEMORY, sizeof (TDIR));
  nDir->lpszPath = HeapAlloc (GetProcessHeap (), HEAP_ZERO_MEMORY,
                                            (dwResult + 2) * sizeof (TCHAR));
  dwResult = GetFullPathName (lpszName, dwResult, nDir->lpszPath, &lpszFile);
  HeapFree (GetProcessHeap (), 0, lpszName);
  if (dwResult <= 0)
    {
      HeapFree (GetProcessHeap (), 0, nDir->lpszPath);
      HeapFree (GetProcessHeap (), 0, nDir);
      errno = ENOTDIR;
      return NULL;
    }
  if (nDir->lpszPath[dwResult - 1] != '\\')
    lstrcat (nDir->lpszPath, _T("\\"));
  lstrcat (nDir->lpszPath, _T("*"));
  hFind = FindFirstFile (nDir->lpszPath, &fnData);
  if (hFind == INVALID_HANDLE_VALUE)
    {
      HeapFree (GetProcessHeap (), 0, nDir->lpszPath);
      HeapFree (GetProcessHeap (), 0, nDir);
      errno = ENOTDIR;
      return NULL;
    }
  if (!FindClose (hFind))
    {
      HeapFree (GetProcessHeap (), 0, nDir->lpszPath);
      HeapFree (GetProcessHeap (), 0, nDir);
      errno = EFAULT;
      return NULL;
    }
  nDir->hFind = INVALID_HANDLE_VALUE;
  errno = 0;
  return nDir;
}


struct tdirent *
treaddir (TDIR *nDir)
{
  WIN32_FIND_DATA fnData;

  if (!nDir)
    {
      errno = EFAULT;
      return NULL;
    }
  if (nDir->nStat == 0)
    {
      nDir->hFind = FindFirstFile (nDir->lpszPath, &fnData);
      nDir->nStat = nDir->hFind == INVALID_HANDLE_VALUE ? -1 : 1;
    }
  else if (nDir->nStat > 0)
    {
      if (FindNextFile (nDir->hFind, &fnData))
        {
          nDir->nStat++;
        }
      else
        {
          FindClose (nDir->hFind);
          nDir->hFind = INVALID_HANDLE_VALUE;
          nDir->nStat = -1;
        }
    }
  errno = 0;
  if (nDir->nStat <= 0)
    return NULL;
  nDir->dd_dir.d_namlen = lstrlen (fnData.cFileName);
  lstrcpy (nDir->dd_dir.d_name, fnData.cFileName);
  return &nDir->dd_dir;
}


int
tclosedir (TDIR *nDir)
{
  int result;

  if (nDir)
    {
      result = nDir->hFind == INVALID_HANDLE_VALUE || FindClose (nDir->hFind)
                                                                    ? 0 : -1;
      HeapFree (GetProcessHeap (), 0, nDir->lpszPath);
      HeapFree (GetProcessHeap (), 0, nDir);
      errno = 0;
    }
  else
    {
      result = -1;
      errno = EFAULT;
    }
  return result;
}


void
trewinddir (TDIR *nDir)
{
  if (nDir)
    {
      if (nDir->hFind != INVALID_HANDLE_VALUE)
        {
          FindClose (nDir->hFind);
          nDir->hFind = INVALID_HANDLE_VALUE;
        }
      nDir->nStat = 0;
      errno = 0;
    }
  else
    {
      errno = EFAULT;
    }
}


long
ttelldir (TDIR *nDir)
{
  return nDir ? (errno = 0, nDir->nStat) : (errno = EFAULT, -1);
}


void
tseekdir (TDIR *nDir,
          long  pos)
{
  if (!nDir)
    {
      errno = EFAULT;
      return;
    }
  if (pos < 0)
    {
      if (nDir->hFind != INVALID_HANDLE_VALUE)
        {
          FindClose (nDir->hFind);
          nDir->hFind = INVALID_HANDLE_VALUE;
        }
      nDir->nStat = -1;
    }
  else
    {
      trewinddir (nDir);
      while ((nDir->nStat < pos) && treaddir (nDir));
    }
  errno = 0;
}
