/***************************************************************************
 *   copyright           : (C) 2002 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.de                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <gtincl.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
/* #include <sys/mman.h> */
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>


void* mem_realloc (void* oldpointer, size_t size) {
  void* retval;
    
  if ((retval=realloc(oldpointer,size))==NULL && size>0) {
    fprintf(stderr,"%s\n",_("Memory allocation failure"));
    exit(EXIT_FAILURE);
  }
  return retval;
}

void* mem_alloc (size_t size, short zero_it) {
  void* retval;

  retval=mem_realloc(NULL,size);
  if (zero_it) {
    memset(retval,0,size);
  }
  return retval;
}

int mem_map(char* file, struct mmapped_file* fs) {
  struct stat s;
  int fd;
  off_t counter = 0;
  ssize_t status = 0;

  if ((fd = open (file, O_RDONLY)) < 0) return -1;
  if (fstat(fd,&s) < 0) return -1;
  fs->size = s.st_size;
/*   fs->ptr = mmap(NULL,fs->size,PROT_READ,MAP_PRIVATE,fd,0); */
/*   if (fs->ptr == MAP_FAILED) return -1; */
  fs->ptr = mem_alloc(fs->size,1);
  do {
    status = read(fd,((uint8_t*)fs->ptr)+counter,fs->size);
    if (status == -1 &&
	errno != EAGAIN && errno != EINTR) {
      fs->ptr = mem_realloc(fs->ptr,0);
      return -1;
    }
    counter += status;
  } while (counter < fs->size);
  if (close(fd) < 0)  return -1;

  return 0;
}

void mem_unmap (struct mmapped_file* fs) {
/*   if (munmap(fs->ptr,fs->size) < 0) { */
/*     fprintf(stderr,"%s: %s\n","Error",strerror(errno)); */
/*     exit(EXIT_FAILURE); */
/*   } */
  fs->ptr = mem_realloc(fs->ptr,(fs->size=0));
}
