/* Fonctions de gestion de fichiers             */
/*                                              */
/* Auteur: Nicolas JANEY                        */
/* nicolas.janey@univ-fcomte.fr                 */
/* Novembre 2012                                */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <io.h>
#include <math.h>

/* Taille d'un fichier                          */

long long fileSize(char *filename) {
  char rep[512];
  strcpy(rep,filename);
  { int len =(int) strlen(rep)-1;
    while ( rep[len] == ' ' ) {
      rep[len] = 0x00;
      len--; } }
  struct _finddatai64_t c_file;
  intptr_t hFile;
  if( (hFile = _findfirst64(rep,&c_file)) == -1L ) {
    _findclose(hFile);
    return(-1); }
  long long size = c_file.size;
  _findclose(hFile);
  return(size);
}

/* Lecture d'un fichier                         */

char *loadFile(char *filename) {
  static size_t bufferSize = 2000000;
  size_t size =(size_t) fileSize(filename);
  printf("%lld\n",(long long) size);
  if ( size == -1 )
    return(NULL);
  char *img =(char *) calloc(size,sizeof(char));
  printf("%p\n",img);
  if ( !img )
    return(NULL);
  FILE *f = fopen(filename,"rb");
  if ( !f ) {
    free(img);
    return(NULL); }
  size_t iter = (size+bufferSize-1)/bufferSize;
  for ( size_t i = 0 ; i < iter ; i++ ) {
    printf("*");
    size_t sz = size-i*bufferSize;
    if ( sz > bufferSize )
      sz = bufferSize;
    fread(&img[i*bufferSize],sz,1,f); }
  printf("\n");
  fclose(f);
  return(img);
} 

int existe(char *filename) {
  char rep[512];
  strcpy(rep,filename);
  { int len =(int) strlen(rep)-1;
    while ( rep[len] == ' ' ) {
      rep[len] = 0x00;
      len--; } }
  struct _finddatai64_t c_file;
  intptr_t hFile;
  if( (hFile = _findfirst64(rep,&c_file)) == -1L ) {
    _findclose(hFile);
    return(0); }
  _findclose(hFile);
  return(1);
}
