#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif


#ifdef HAVE_MMAP
# include <unistd.h>
# else
# ifndef _WIN32
#  include <glib.h>
# endif
#endif

#include "mapfile.h"


bool TMapFile::open(const char *file_name)
{
#ifdef HAVE_MMAP
  if((mmap_fd = ::open(file_name, O_RDONLY ))<0){
    //g_message("Open file %s failed!\n",idxfilename);
    return false;
  }
  struct stat info;
  fstat(mmap_fd, &info);  
  file_size=info.st_size;
  data_buffer = (char *)mmap(NULL, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0);
  if ((void *)data_buffer == (void *)(-1)) {
    //g_message("mmap file %s failed!\n",idxfilename);
    ::close(mmap_fd);
    data_buffer=NULL;
    return false;
  }
#else
  if(!g_file_get_contents(file_name, &data_buffer, &file_size, NULL))
    return false;
#endif
  return true;
}


bool TMapFile::open(const char *file_name, size_t _file_size)
{
  file_size=_file_size;
#ifdef HAVE_MMAP
  if((mmap_fd = ::open(file_name, O_RDONLY ))<0){
    //g_message("Open file %s failed!\n",idxfilename);
    return false;
  } 
  data_buffer = (char *)mmap(NULL, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0);
  if ((void *)data_buffer == (void *)(-1)) {
    //g_message("mmap file %s failed!\n",idxfilename);
    ::close(mmap_fd);
    data_buffer=NULL;
    return false;
  }
  
#else
#ifdef _WIN32
  hFile = CreateFile(file_name, GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0,  file_size, NULL);
  data_buffer = (gchar *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, file_size);
#else
  if(!g_file_get_contents(file_name, &data_buffer, &file_size, NULL))
    return false;
#endif
#endif
  return true;
}
void TMapFile::close(void)
{
#ifdef HAVE_MMAP
  if(data_buffer){
    munmap(data_buffer, file_size);
    data_buffer = NULL;
    file_size = 0;
    ::close(mmap_fd);
    mmap_fd = -1;
  }
#else
#  ifdef _WIN32
  if(data_buffer){
    UnmapViewOfFile(data_buffer);
    data_buffer = NULL;
    CloseHandle(hFileMap);
    CloseHandle(hFile);
  }
#  else
  g_free(data_buffer);
  data_buffer = NULL;
#  endif
#endif
}
