/* w32-ce.h 
   Copyright (C) 2010 g10 Code GmbH
   Copyright (C) 1991,92,97,2000,02 Free Software Foundation, Inc.

   This file is part of GPGME.
 
   GPGME is free software; you can redistribute it and/or modify it
   under the terms of the GNU Lesser General Public License as
   published by the Free Software Foundation; either version 2.1 of
   the License, or (at your option) any later version.
   
   GPGME 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.  See the GNU
   Lesser General Public License for more details.
   
   You should have received a copy of the GNU Lesser General Public
   License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <errno.h>
#include <string.h>
#include <gpg-error.h>

#include <windows.h>

/* Return a malloced wide char string from an UTF-8 encoded input
   string STRING.  Caller must free this value.  Returns NULL and sets
   ERRNO on failure.  Calling this function with STRING set to NULL is
   not defined.  */
wchar_t *
utf8_to_wchar (const char *string)
{
  int n;
  size_t nbytes;
  wchar_t *result;

  n = MultiByteToWideChar (CP_UTF8, 0, string, -1, NULL, 0);
  if (n < 0)
    {
      gpg_err_set_errno (EINVAL);
      return NULL;
    }

  nbytes = (size_t)(n+1) * sizeof(*result);
  if (nbytes / sizeof(*result) != (n+1)) 
    {
      gpg_err_set_errno (ENOMEM);
      return NULL;
    }
  result = malloc (nbytes);
  if (!result)
    return NULL;

  n = MultiByteToWideChar (CP_UTF8, 0, string, -1, result, n);
  if (n < 0)
    {
      free (result);
      gpg_err_set_errno (EINVAL);
      result = NULL;
    }
  return result;
}

/* Replacement for the access function.  Note that we can't use fopen
   here because wince might now allow to have a shared read for an
   executable; it is better to to read the file attributes.
   
   Limitation:  Only F_OK is supported.
*/
int
_access (const char *fname, int mode)
{
  DWORD attr;
  wchar_t *wfname;

  (void)mode;

  wfname = utf8_to_wchar (fname);
  if (!wfname)
    return -1;

  attr = GetFileAttributes (wfname);
  free (wfname);
  if (attr == (DWORD)(-1))
    {
      gpg_err_set_errno (ENOENT);
      return -1;
    }
  return 0;
}
