/***************************************************************************
 *   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 <helper.h>
#include <gtincl.h>
#include <w32compat.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>

void file_close (int filedes) {
  if (filedes > 2) close(filedes);
}

int file_accessible_ro (char* file) {
  int myfd;
  myfd = open(file,O_RDONLY);
  file_close(myfd);
  if (myfd == -1) return 0;
  else return 1;
}

int file_open_input (char* file) {
  int myfd;
	
  if (str_len(file) && strcmp(file,"-")) {
    myfd = open(file,O_RDONLY);
    if (myfd == -1) {
      errexit(_("Could not access %s: %s\n"),file, strerror(errno));
    }
  } else {
    myfd = STDIN_FILENO;
    file = "stdin";
  }
  print_verbose(1,_("Accessing %s\n"),file);
  if (isatty(myfd)) {
    print_verbose(0,"%s:\n",_("Please input the data and finish with Ctrl-D on an empty line"));
  }
  return(myfd);
}

int file_open_output (char* file) {
  int myfd;

  if (str_len(file) && strcmp(file,"-")) {
    myfd=open(file ,O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP);
    if (myfd==-1){
      file_close(myfd);
      errexit(_("%s could not be created: %s\n"),file, strerror(errno));
    } else {
      print_verbose(1,_("%s created.\n"),file);
    }
  }else{
    myfd=STDOUT_FILENO;
  }
  return(myfd);
}

#define FILE_READ_SIZE 175
unsigned int file_read_binary (char* file, char** buffer) {
  int myfd = file_open_input(file);
  size_t bsize = FILE_READ_SIZE;
  char* b = mem_alloc(bsize*sizeof(*b),0);
  unsigned int count = 0;
  int status = 1;

  while (status > 0) {
    if (count >= bsize) {
      bsize += FILE_READ_SIZE;
      b = mem_realloc(b,bsize*sizeof(*b));
    }
    while (status > 0 && count < bsize) {
      status = read(myfd,b+count,bsize-count);
      if (status > 0) count += status;
      else if (status < 0) {
	/* FIXME: check for harmless errors */
	print_error("%s\n", strerror(errno));
	mem_realloc(b,0);
	file_close(myfd);
	return 0;
      }
    }
  }
  file_close(myfd);
  *buffer = b;
  print_verbose(1,ngettext("%s has %d byte.\n",
			   "%s has %d bytes.\n",
			   count),
		file,count);
  return count;
}
